source: projects/synaptic/trunk/gtk/gsynaptic.cc @ 280

Revision 280, 16.8 KB checked in by yasumichi, 15 years ago (diff)

first import

Line 
1/* gsynaptic.cc - main()
2 *
3 * Copyright (c) 2001-2003 Alfredo K. Kojima
4 *
5 * Author: Alfredo K. Kojima <kojima@conectiva.com.br>
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 2 of the
10 * License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 * USA
21 */
22
23#include <iostream>
24
25#include "config.h"
26
27#include "i18n.h"
28
29#include "rconfiguration.h"
30#include "raptoptions.h"
31#include "rpackagelister.h"
32#include <cmath>
33#include <apt-pkg/configuration.h>
34#include <apt-pkg/cmndline.h>
35#include <apt-pkg/error.h>
36#include <X11/Xlib.h>
37#include <unistd.h>
38#include <sys/types.h>
39#include <sys/stat.h>
40#include <fcntl.h>
41#include <signal.h>
42#include <cassert>
43#include <errno.h>
44#include <fstream>
45
46#include "rgmainwindow.h"
47#include "rguserdialog.h"
48#include "locale.h"
49#include "stdio.h"
50#include "rgmisc.h"
51
52
53
54typedef enum {
55   UPDATE_ASK,
56   UPDATE_CLOSE,
57   UPDATE_AUTO
58} UpdateType;
59
60
61bool ShowHelp(CommandLine & CmdL)
62{
63   std::cout <<
64#ifndef HAVE_RPM
65      PACKAGE " for Debian " VERSION
66#else
67      _config->Find("Synaptic::MyName", PACKAGE) + " " VERSION
68#endif
69      "\n\n" <<
70      _("Usage: synaptic [options]\n") <<
71      _("-h   This help text\n") <<
72      _("-r   Open in the repository screen\n") <<
73      _("-f=? Give an alternative filter file\n") <<
74      _("-t   Give an alternative main window title (e.g. hostname with `uname -n`)\n") <<
75      _("-i=? Start with the initial Filter with given name\n") <<
76      _("-o=? Set an arbitary configuration option, eg -o dir::cache=/tmp\n")<<
77      _("--upgrade-mode  Call Upgrade and display changes\n") <<
78      _("--dist-upgrade-mode  Call DistUpgrade and display changes\n") <<
79      _("--update-at-startup  Call \"Reload\" on startup\n")<<
80      _("--non-interactive Never prompt for user input\n") << 
81      _("--task-window Open with task window\n") <<
82      _("--add-cdrom Add a cdrom at startup (needs path for cdrom)\n") <<
83      _("--ask-cdrom Ask for adding a cdrom and exit\n");
84   exit(0);
85}
86
87CommandLine::Args Args[] = {
88   {
89   'h', "help", "help", 0}
90   , {
91   'f', "filter-file", "Volatile::filterFile", CommandLine::HasArg}
92   , {
93   'r', "repositories", "Volatile::startInRepositories", 0}
94   , {
95   'i', "initial-filter", "Volatile::initialFilter", CommandLine::HasArg}
96   , {
97   0, "set-selections", "Volatile::Set-Selections", 0}
98   , {
99   0, "set-selections-file", "Volatile::Set-Selections-File", CommandLine::HasArg}
100   , {
101   0, "non-interactive", "Volatile::Non-Interactive", 0}
102   , {
103   0, "upgrade-mode", "Volatile::Upgrade-Mode", 0}
104   , {
105   0, "dist-upgrade-mode", "Volatile::DistUpgrade-Mode", 0}
106   , {
107   0, "add-cdrom", "Volatile::AddCdrom-Mode", CommandLine::HasArg}
108   , {
109   0, "ask-cdrom", "Volatile::AskCdrom-Mode", 0}
110   , {
111   0, "plug-progress-into", "Volatile::PlugProgressInto", CommandLine::HasArg}
112   , {
113   0, "progress-str", "Volatile::InstallProgressStr", CommandLine::HasArg} 
114   , {
115   0, "finish-str", "Volatile::InstallFinishedStr", CommandLine::HasArg} 
116   , {
117   't', "title", "Volatile::MyName", CommandLine::HasArg}
118   , {
119   0, "update-at-startup", "Volatile::Update-Mode", 0}
120   , {
121   0, "hide-main-window", "Volatile::HideMainwindow", 0}
122   , {
123   0, "task-window", "Volatile::TaskWindow", 0}
124   , {
125   'o', "option", 0, CommandLine::ArbItem}
126   , {
127   0, 0, 0, 0}
128};
129
130
131static void SetLanguages()
132{
133   string LangList;
134   if (_config->FindB("Synaptic::DynamicLanguages", true) == false) {
135      LangList = _config->Find("Synaptic::Languages", "");
136   } else {
137      char *lang = getenv("LANG");
138      if (lang == NULL) {
139         lang = getenv("LC_MESSAGES");
140         if (lang == NULL) {
141            lang = getenv("LC_ALL");
142         }
143      }
144      if (lang != NULL && strcmp(lang, "C") != 0)
145         LangList = lang;
146   }
147
148   _config->Set("Volatile::Languages", LangList);
149}
150
151void welcome_dialog(RGMainWindow *mainWindow)
152{
153      // show welcome dialog
154      if (_config->FindB("Synaptic::showWelcomeDialog", true) &&
155          !_config->FindB("Volatile::Upgrade-Mode",false)) {
156         RGGladeUserDialog dia(mainWindow);
157         dia.run("welcome");
158         GtkWidget *cb = glade_xml_get_widget(dia.getGladeXML(),
159                                              "checkbutton_show_again");
160         assert(cb);
161         _config->Set("Synaptic::showWelcomeDialog",
162                      gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cb)));
163      }
164}
165
166void update_check(RGMainWindow *mainWindow, RPackageLister *lister)
167{
168   struct stat st;
169
170   // check when the last update happend updates
171   UpdateType update =
172      (UpdateType) _config->FindI("Synaptic::update::type", UPDATE_ASK);
173   if(update != UPDATE_CLOSE) {
174      // check when last update happend
175      int lastUpdate = _config->FindI("Synaptic::update::last",0);
176      int minimal= _config->FindI("Synaptic::update::minimalIntervall", 48);
177
178      // check for the mtime of the various package lists
179      vector<string> filenames = lister->getPolicyArchives(true);
180      for (int i=0;i<filenames.size();i++) {
181         stat(filenames[i].c_str(), &st);
182         if(filenames[i] != "/var/lib/dpkg/status")
183            lastUpdate = max(lastUpdate, (int)st.st_mtime);
184      }
185     
186      // new apt uses this
187      string update_stamp = _config->FindDir("Dir::State","var/lib/apt");
188      update_stamp += "update-stamp";
189      if(FileExists(update_stamp)) {
190         stat(update_stamp.c_str(), &st);
191         lastUpdate = max(lastUpdate, (int)st.st_mtime);
192      }
193
194      // 3600s=1h
195      if((lastUpdate + minimal*3600) < time(NULL)) {
196         if(update == UPDATE_AUTO) 
197            mainWindow->cbUpdateClicked(NULL, mainWindow);
198         else {
199            RGGladeUserDialog dia(mainWindow);
200            int res = dia.run("update_outdated",true);
201            GtkWidget *cb = glade_xml_get_widget(dia.getGladeXML(),
202                                                 "checkbutton_remember");
203            assert(cb);
204            if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(cb))) {
205               if(res == GTK_RESPONSE_CANCEL)
206                  _config->Set("Synaptic::update::type", UPDATE_CLOSE);
207               if(res == GTK_RESPONSE_OK)
208                  _config->Set("Synaptic::update::type", UPDATE_AUTO);
209            }
210            if(res == GTK_RESPONSE_OK)
211               mainWindow->cbUpdateClicked(NULL, mainWindow);
212         }
213      }
214   }
215}
216
217
218// lock stuff
219static int sigterm_unix_signal_pipe_fds[2];
220static GIOChannel *sigterm_iochn;
221
222static void 
223handle_sigusr1 (int value)
224{
225   static char marker[1] = {'S'};
226
227   /* write a 'S' character to the other end to tell about
228    * the signal. Note that 'the other end' is a GIOChannel thingy
229    * that is only called from the mainloop - thus this is how we
230    * defer this since UNIX signal handlers are evil
231    *
232    * Oh, and write(2) is indeed reentrant */
233   write (sigterm_unix_signal_pipe_fds[1], marker, 1);
234}
235
236static gboolean
237sigterm_iochn_data (GIOChannel *source, 
238                    GIOCondition condition, 
239                    gpointer user_data)
240{
241   GError *err = NULL;
242   gchar data[1];
243   gsize bytes_read;
244   
245   RGMainWindow *me = (RGMainWindow *)user_data;
246
247   /* Empty the pipe */
248   if (G_IO_STATUS_NORMAL != 
249       g_io_channel_read_chars (source, data, 1, &bytes_read, &err)) {
250      g_warning("Error emptying callout notify pipe: %s", err->message);
251      g_error_free (err);
252      return TRUE;
253   }
254   if(data[0] == 'S')
255      me->activeWindowToForeground();
256
257   return TRUE;
258}
259
260// test if a lock is aquired already, return 0 if no lock is found,
261// the pid of the locking application or -1 on error
262pid_t TestLock(string File)
263{
264   int FD = open(File.c_str(),0);
265   if(FD < 0) {
266      if(errno == ENOENT) {
267         // File does not exist, no there can't be a lock
268         return 0; 
269      } else {
270         //cout << "open, errno: " << errno << endl;
271         //perror("open");
272         return(-1);
273      }
274   }
275   struct flock fl;
276   fl.l_type = F_WRLCK;
277   fl.l_whence = SEEK_SET;
278   fl.l_start = 0;
279   fl.l_len = 0;
280   if (fcntl(FD, F_GETLK, &fl) < 0) {
281      int Tmp = errno;
282      close(FD);
283      cerr << "fcntl error" << endl;
284      errno = Tmp;
285      return(-1);
286   }
287   close(FD);
288   // lock is available
289   if(fl.l_type == F_UNLCK)
290      return(0);
291   // file is locked by another process
292   return (fl.l_pid);
293}
294
295// check if we can get a lock, must be done after we read the configuration
296// if a lock is found and the app is synaptic send it a "come to foreground"
297// signal (USR1) or if not synaptic display a error and exit
298// 1. check if there is another synaptic running
299//    a) if so, check if it runs interactive and we are not running interactive
300//       *) if so, send signal and show message
301//       *) if not, send signal
302// 2. check if we can get a /var/lib/dpkg/lock
303//    *) if not, show message and fail
304void check_and_aquire_lock()
305{
306   GtkWidget *dia;
307   gchar *msg = NULL;
308   pid_t LockedApp, runsNonInteractive;
309   bool weNonInteractive;
310
311   string SynapticLock = RConfDir()+"/lock";
312   string SynapticNonInteractiveLock = RConfDir()+"/lock.non-interactive";
313   weNonInteractive = _config->FindB("Volatile::Non-Interactive", false);
314
315   // 1. test for another synaptic
316   LockedApp = TestLock(SynapticLock);
317   if(LockedApp > 0) {
318      runsNonInteractive = TestLock(SynapticNonInteractiveLock);
319      //cout << "runsNonIteractive: " << runsNonInteractive << endl;
320      //cout << "weNonIteractive: " << weNonInteractive << endl;
321      if(weNonInteractive && runsNonInteractive <= 0) {
322         // message that we can't turn a non-interactive into a interactive
323         // one
324         msg = g_strdup_printf("<big><b>%s</b></big>\n\n%s",
325                               _("Another synaptic is running"),
326                               _("There is another synaptic running in "
327                                 "interactive mode. Please close it first. "
328                                 ));
329      } else if(!weNonInteractive && runsNonInteractive) {
330         msg = g_strdup_printf("<big><b>%s</b></big>\n\n%s",
331                               _("Another synaptic is running"),
332                               _("There is another synaptic running in "
333                                 "non-interactive mode. Please wait for it "
334                                 "to finish first."
335                                 ));
336      }
337
338      if(msg != NULL) {
339         dia = gtk_message_dialog_new_with_markup(NULL, GTK_DIALOG_MODAL,
340                                                  GTK_MESSAGE_ERROR, 
341                                                  GTK_BUTTONS_CLOSE, msg);
342         gtk_dialog_run(GTK_DIALOG(dia));
343         gtk_widget_destroy(dia);
344         g_free(msg);
345      }
346
347      cout << "Another synaptic is running. Trying to bring it to the foreground" << endl;
348      kill(LockedApp, SIGUSR1);
349      exit(0);
350   }
351
352   // 2. test if we can get a lock
353   string AdminDir = flNotFile(_config->Find("Dir::State::status"));
354   LockedApp = TestLock(AdminDir + "lock");
355   if (LockedApp > 0) {
356      msg = g_strdup_printf("<big><b>%s</b></big>\n\n%s",
357                            _("Unable to get exclusive lock"),
358                            _("This usually means that another "
359                              "package management application "
360                              "(like apt-get or aptitude) "
361                              "already running. Please close that "
362                              "application first."));
363      dia = gtk_message_dialog_new_with_markup(NULL, GTK_DIALOG_MODAL,
364                                               GTK_MESSAGE_ERROR, 
365                                               GTK_BUTTONS_CLOSE, msg);
366      gtk_dialog_run(GTK_DIALOG(dia));
367      g_free(msg);
368      exit(0);
369   }
370   
371   // we can't get a lock?!?
372   if(GetLock(SynapticLock, true) < 0) {
373      _error->DumpErrors();
374      exit(1);
375   }
376   // if we run nonInteracitvely, get a seond lock
377   if(weNonInteractive && GetLock(SynapticNonInteractiveLock, true) < 0) {
378      _error->DumpErrors();
379      exit(1);
380   }
381}
382
383int main(int argc, char **argv)
384{
385#ifdef ENABLE_NLS
386   //bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
387   bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR);
388   textdomain(GETTEXT_PACKAGE);
389
390#ifdef HAVE_RPM
391   bind_textdomain_codeset("rpm", "UTF-8");
392#endif
393#endif
394
395   gtk_init(&argc, &argv);
396   //XSynchronize(dpy, 1);
397
398   if (getuid() != 0) {
399      RGUserDialog userDialog;
400      userDialog.error(_("You must run this program as the root user."));
401      exit(1);
402   }
403
404   if (!RInitConfiguration("synaptic.conf")) {
405      RGUserDialog userDialog;
406      userDialog.showErrors();
407      exit(1);
408   }
409
410   // read the cmdline
411   CommandLine CmdL(Args, _config);
412   if (CmdL.Parse(argc, (const char **)argv) == false) {
413      RGUserDialog userDialog;
414      userDialog.showErrors();
415      exit(1);
416   }
417   
418   bool UpdateMode = _config->FindB("Volatile::Update-Mode",false);
419   bool NonInteractive = _config->FindB("Volatile::Non-Interactive", false);
420
421   // check if there is another application runing and
422   // act accordingly
423   check_and_aquire_lock();
424
425   // read configuration early
426   _roptions->restore();
427
428   if (_config->FindB("help") == true)
429      ShowHelp(CmdL);
430
431#ifdef ENABLE_NLS
432   bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
433#endif
434
435   SetLanguages();
436
437   // init the static pkgStatus class. this loads the status pixmaps
438   // and colors
439   RGPackageStatus::pkgStatus.init();
440
441   RPackageLister *packageLister = new RPackageLister();
442   RGMainWindow *mainWindow = new RGMainWindow(packageLister, "main");
443
444   // install a sigusr1 signal handler and put window into
445   // foreground when called. use the io_watch trick because gtk is not
446   // reentrant
447   // SIGUSR1 handling via pipes 
448   if (pipe (sigterm_unix_signal_pipe_fds) != 0) {
449      g_warning ("Could not setup pipe, errno=%d", errno);
450      return 1;
451   }
452   sigterm_iochn = g_io_channel_unix_new (sigterm_unix_signal_pipe_fds[0]);
453   if (sigterm_iochn == NULL) {
454      g_warning("Could not create GIOChannel");
455      return 1;
456   }
457   g_io_add_watch (sigterm_iochn, G_IO_IN, sigterm_iochn_data, mainWindow);
458   signal (SIGUSR1, handle_sigusr1);
459   // -------------------------------------------------------------
460
461   // read which default distro to use
462   string s = _config->Find("Synaptic::DefaultDistro", "");
463   if (s != "")
464      _config->Set("APT::Default-Release", s);
465
466#ifndef HAVE_RPM
467   mainWindow->setTitle(_("Synaptic Package Manager "));
468#else
469   mainWindow->setTitle(_config->Find("Synaptic::MyName", "Synaptic"));
470#endif
471   // this is for stuff like "synaptic -t `uname -n`"
472   s = _config->Find("Volatile::MyName","");
473   if(s.size() > 0)
474      mainWindow->setTitle(s);
475   
476   if(_config->FindB("Volatile::HideMainwindow", false))
477      mainWindow->hide();
478   else
479      mainWindow->show();
480
481   RGFlushInterface();
482
483   mainWindow->setInterfaceLocked(true);
484
485   string cd_mount_point = _config->Find("Volatile::AddCdrom-Mode", "");
486   if(!cd_mount_point.empty()) {
487      _config->Set("Acquire::cdrom::mount",cd_mount_point);
488      _config->Set("APT::CDROM::NoMount", true);
489      mainWindow->cbAddCDROM(NULL, mainWindow);
490   } else if(_config->FindB("Volatile::AskCdrom-Mode",false)) {
491      mainWindow->cbAddCDROM(NULL, mainWindow);
492      return 0;
493   }
494
495   //no need to open a cache that will invalid after the update
496   if(!UpdateMode) {
497      mainWindow->setTreeLocked(true);
498      packageLister->openCache();
499      mainWindow->restoreState();
500      mainWindow->showErrors();
501      mainWindow->setTreeLocked(false);
502   }
503   
504   if (_config->FindB("Volatile::startInRepositories", false)) {
505      mainWindow->cbShowSourcesWindow(NULL, mainWindow);
506   }
507
508   // selections from stdin
509   if (_config->FindB("Volatile::Set-Selections", false) == true) {
510      packageLister->unregisterObserver(mainWindow);
511      packageLister->readSelections(cin);
512      packageLister->registerObserver(mainWindow);
513   }
514
515   // selections from a file
516   string selections_filename;
517   selections_filename =_config->Find("Volatile::Set-Selections-File", "");
518   if (selections_filename != "") {
519      packageLister->unregisterObserver(mainWindow);
520      ifstream selfile(selections_filename.c_str());
521      packageLister->readSelections(selfile);
522      selfile.close();
523      packageLister->registerObserver(mainWindow);
524   }
525
526   mainWindow->setInterfaceLocked(false);
527
528   if(UpdateMode) {
529      mainWindow->cbUpdateClicked(NULL, mainWindow);
530      mainWindow->setTreeLocked(true);
531      packageLister->openCache();
532      mainWindow->restoreState();
533      mainWindow->setTreeLocked(false);
534      mainWindow->showErrors();
535      mainWindow->changeView(PACKAGE_VIEW_STATUS, _("Installed (upgradable)"));
536   }
537
538   if(_config->FindB("Volatile::Upgrade-Mode",false) 
539      || _config->FindB("Volatile::DistUpgrade-Mode",false) ) {
540      mainWindow->cbUpgradeClicked(NULL, mainWindow);
541      mainWindow->changeView(PACKAGE_VIEW_CUSTOM, _("Marked Changes"));
542   }
543
544   if(_config->FindB("Volatile::TaskWindow",false)) {
545      mainWindow->cbTasksClicked(NULL, mainWindow);
546   }
547
548   string filter = _config->Find("Volatile::initialFilter","");
549   if(filter != "")
550      mainWindow->changeView(PACKAGE_VIEW_CUSTOM, filter);
551
552   if (NonInteractive) {
553      mainWindow->cbProceedClicked(NULL, mainWindow);
554   } else {
555      welcome_dialog(mainWindow);
556#if 0
557      update_check(mainWindow, packageLister);
558#endif
559      gtk_main();
560   }
561
562   return 0;
563}
564
565
566// vim:sts=4:sw=4
Note: See TracBrowser for help on using the repository browser.