Пример #1
0
 def connect_app_signals (self,app):
   """connects standard app signals to appropriate methods."""
   self._app = app;
   QObject.connect(app,PYSIGNAL("solver.begin"),self.xcurry(self.solver_begin,_argslice=slice(1,2)));
   QObject.connect(app,PYSIGNAL("solver.iter"),self.xcurry(self.solver_iter,_argslice=slice(1,2)));
   QObject.connect(app,PYSIGNAL("solver.end"),self.xcurry(self.solver_end,_argslice=slice(1,2)));
   QObject.connect(app,PYSIGNAL("isConnected()"),self.xcurry(self.reset));
Пример #2
0
  def __init__(self,parent,name,name1='',udi_root=None,caption=None,prec=(None,'g'),maxwidth=None):
    self._tw = DataDraggableTreeWidget(ClickableTreeWidget)(parent);
    self._tw.setHeaderLabels([name1,'',name]);
    self._tw.setRootIsDecorated(True);
    self._tw.setSortingEnabled(False);
    self._tw.header().setResizeMode(0,QHeaderView.ResizeToContents);
    self._tw.header().setResizeMode(1,QHeaderView.ResizeToContents);
    self._tw.header().setResizeMode(2,QHeaderView.ResizeToContents);
    self._tw.header().setStretchLastSection(False);
    self._tw.header().setResizeMode(QHeaderView.ResizeToContents);

    self._tw.header().hide();
    setattr(self._tw,'_maxwidth',maxwidth or HierBrowser.MaxWidth);
    # self._tw.header().setResizeMode(QHeaderView.Fixed);
#    for col in (0,1,2):
#      self._tw.setColumnWidthMode(col,QListView.Maximum);
#    self._tw.setFocus();
    QObject.connect(self._tw,SIGNAL('itemExpanded(QTreeWidgetItem*)'),
                     self._expand_item_content);
    QObject.connect(self._tw,PYSIGNAL('mouseButtonClicked()'),self._process_item_click);
    QObject.connect(self._tw,PYSIGNAL('itemContextMenuRequested()'),self._show_context_menu);
#    self._tw.connect(self._tw,SIGNAL('doubleClicked(QListViewItem*)'),
#                     self.display_item);
    # connect the get_drag_item method for drag-and-drop
    self._tw.get_drag_item = self.get_drag_item;
    self._tw.get_drag_item_type = self.get_drag_item_type;
    # enable UDIs, if udi root is not none
    self.set_udi_root(udi_root);
    # initialize precision
    self._tw._prec = prec;
    # for debugging purposes
    QObject.connect(self._tw,SIGNAL("itemClicked(QTreeWidgetItem*)"),self._print_item);
Пример #3
0
 def add_page(self, name=None, icon=None):
     page = Timba.Grid.Page(self,
                            self._maintab,
                            max_nx=self.max_nx,
                            max_ny=self.max_ny)
     wpage = page.wtop()
     wpage._page = page
     _dprint(2, 'name', name, 'icon', icon)
     index = self._maintab.count()
     # generate page name, if none is supplied
     if name is None:
         name = 'Page %d' % (index + 1)
         page.set_name(name, True)
         # auto_name = True
     else:
         page.set_name(name)
     page.set_icon(icon)
     # add page to tab
     icon = icon or QIcon()
     _dprint(2, 'addTab:', name, icon)
     self._maintab.addTab(wpage, icon, name)
     self._maintab.setCurrentIndex(index)
     QWidget.connect(wpage, PYSIGNAL("layoutChanged()"),
                     self._set_layout_button)
     wpage._change_icon = curry(self._maintab.setTabIcon, index)
     QWidget.connect(wpage, PYSIGNAL("setIcon()"), wpage._change_icon)
     wpage._rename = curry(self._maintab.setTabText, index)
     QWidget.connect(wpage, PYSIGNAL("setName()"), wpage._rename)
     return page
Пример #4
0
    def __init__(self, gw, dataitem, cellspec={}, default_open=None, **opts):
        GriddedPlugin.__init__(self, gw, dataitem, cellspec=cellspec)
        HierBrowser.__init__(self,
                             self.wparent(),
                             "value",
                             "field",
                             udi_root=dataitem.udi)
        # adjust columns when font changes
        QObject.connect(self.wtop(), PYSIGNAL("fontChanged()"),
                        self._resize_sections)

        self.set_widgets(self.wtop(), dataitem.caption, icon=self.icon())
        self._rec = None
        self._default_open = default_open
        if dataitem.data is not None:
            self.set_data(dataitem)
        # add number format menu
        context_menu = self.cell_menu()
        if context_menu is not None:
            context_menu.addSeparator()
            _dprint(3, self.get_precision())
            menu = PrecisionPopupMenu(context_menu, prec=self.get_precision())
            qa = context_menu.addMenu(menu)
            qa.setIcon(pixmaps.precplus.icon())
            qa.setText('Number format')
            QWidget.connect(menu, PYSIGNAL("setPrecision()"),
                            self._set_prec_from_menu)
Пример #5
0
 def __init__(self, name, page, parent):
     QObject.__init__(self, parent)
     QObject.connect(self, PYSIGNAL("updated()"), parent,
                     PYSIGNAL("updated()"))
     self.name = name
     self.page = page
     self.rec = record(name=name, page=page)
Пример #6
0
 def _allocate_grid(self, **kwds):
     """Allocates self._cells: a grid of cells from a workspace.
 All keywords are passed to gridded_workspace.allocate_cells()."""
     # if a previous position in grid was saved, try to reuse it
     if hasattr(self, '_gridpos'):
         kwds['position'] = self._gridpos
     self._cells = self._gw.allocate_cells(nrow=self._nrow,
                                           ncol=self._ncol,
                                           udi=self._dataitem.udi,
                                           **kwds)
     if not self._cells:
         raise Timba.Grid.Error, "unable to allocate cells"
     # save new position
     leadcell = self._cells[0]
     self._gridpos = leadcell.grid_position()
     _dprint(2, id(self), ': allocated', len(self._cells),
             'cells at position', self._gridpos)
     # connect signal: remove dataitem when cells are closed
     leadcell.connect(
         PYSIGNAL("wiped()"),
         self._currier.xcurry(Timba.Grid.Services.removeDataItem,
                              _args=(self._dataitem, ),
                              _argslice=slice(0)))
     # connect signal: float cells
     leadcell.connect(PYSIGNAL("float()"), self.float_cells)
Пример #7
0
 def _allocate_float(self):
     """internal helper func: creates a float window when first called."""
     try:
         float_window = self._float_window
     except AttributeError:
         self._float_window = float_window = Timba.Grid.Floater(
             self._gw.wtop())
         QObject.connect(float_window, PYSIGNAL("closed()"), self._unfloat)
         float_window.setWindowTitle(self._dataitem.name)
         # allocate single cell or grid
         if self._totsize == 1:
             # notitle=True: do not create cell titlebar
             cell = Timba.Grid.Cell(float_window, (0, 0), notitle=True)
             self._float_cells = (cell, )
             float_window.setCentralWidget(cell.wtop())
         else:
             self._float_grid = Timba.Grid.Page(self._gw, float_window,
                                                self._ncol, self._nrow)
             # allocate grid of fixed cells (fixed means no drop support and
             # no change of viewer allowed)
             self._float_cells = self._float_grid.allocate_cells(
                 nrow=self._nrow, ncol=self._ncol, fixed_cells=True)
             float_window.setCentralWidget(self._float_grid.wtop())
     # connect signal: remove dataitem when cells are closed
     self._float_cells[0].connect(PYSIGNAL("closed()"), self.close)
     return float_window
Пример #8
0
 def __init__(self, name, udi, parent, viewer=None):
     QObject.__init__(self, parent)
     QObject.connect(self, PYSIGNAL("updated()"), parent,
                     PYSIGNAL("updated()"))
     self.name = name
     self.rec = record(name=name, udi=udi)
     # resolve viewer to actual viewer class (or None if none specified),
     # and rec.viewer to viewer name; set icon based on viewer
     if viewer is None:
         self.icon = QIcon
         self.enabled = True
         self.viewer = None
     else:
         if isinstance(viewer, str):
             self.rec.viewer = viewer
             self.viewer = Grid.Services.getViewerByName(viewer)
         elif callable(viewer):
             self.rec.viewer = getattr(viewer, 'viewer_name',
                                       viewer.__name__)
             self.viewer = viewer
         else:
             raise TypeError("illegal viewer argument " + str(viewer))
         if self.viewer is not None:
             self.icon = getattr(self.viewer, 'icon', QIcon)
             self.enabled = True
         else:
             self.icon = QIcon
             self.enabled = False
Пример #9
0
    def __init__(self, parent, max_nx=4, max_ny=4, use_hide=None):
        # dictionary of UDIs -> list of GridDataItem objects
        self._dataitems = dict()
        # highlighted item
        self._highlight = None
        # currier
        self._currier = PersistentCurrier()
        self.curry = self._currier.curry
        self.xcurry = self._currier.xcurry

        self._maintab = QTabWidget(parent)
        self._maintab.setTabPosition(QTabWidget.North)
        QWidget.connect(self._maintab, SIGNAL("currentChanged(int)"),
                        self._set_layout_button)
        self.max_nx = max_nx
        self.max_ny = max_ny
        # set of parents for corners of the maintab (added on demand when GUI is built)
        self._tb_corners = {}
        #------ add page
        newpage = self.add_tool_button(
            Qt.TopLeftCorner,
            pixmaps.tab_new_raised.icon(),
            tooltip="open new page. You can also drop data items here.",
            class_=self.DataDropButton,
            click=self.add_page)
        newpage._dropitem = xcurry(Timba.Grid.Services.addDataItem,
                                   _argslice=slice(0, 1),
                                   newpage=True)
        QWidget.connect(newpage, PYSIGNAL("itemDropped()"), newpage._dropitem)
        #------ new panels button
        self._new_panel = self.add_tool_button(
            Qt.TopLeftCorner,
            pixmaps.view_right.icon(),
            tooltip=
            "add more panels to this page. You can also drop data items here.",
            class_=self.DataDropButton,
            click=self._add_more_panels)
        self._new_panel._dropitem = xcurry(Timba.Grid.Services.addDataItem,
                                           _argslice=slice(0, 1),
                                           newcell=True)
        QWidget.connect(self._new_panel, PYSIGNAL("itemDropped()"),
                        self._new_panel._dropitem)
        #------ align button
        self.add_tool_button(Qt.TopLeftCorner,
                             pixmaps.view_split.icon(),
                             tooltip="align panels on this page",
                             click=self._align_grid)
        #------ remove page
        self.add_tool_button(Qt.TopRightCorner,
                             pixmaps.tab_remove.icon(),
                             tooltip="remove this page",
                             click=self.remove_current_page)
        # init first page
        self.add_page()
Пример #10
0
 def execute_tdl_job(self, _tdlmod, ns, func, name, job_id):
     """executes a predefined TDL job given by func"""
     self._tdlexec_menu.hide()
     try:
         # log job
         TDLOptions.dump_log(
             "running TDL job '%s' (%s)" %
             (name, ("job id '%s'" % job_id if job_id else "no job id")))
         busy = BusyIndicator()
         func(meqds.mqs(), self)
         # no errors, so clear error list, if any
         self.clear_errors()
         self.show_message("TDL job '" + name + "' executed.",
                           transient=True)
         busy = None
     except:
         (etype, exc, tb) = sys.exc_info()
         _dprint(0, 'exception running TDL job', func.__name__)
         traceback.print_exception(etype, exc, tb)
         # use TDL add_error() to process the error, since this automatically
         # adds location information. However, we want to remove ourselves
         # from the stack traceback first
         tb = traceback.extract_tb(tb)
         # pop everything leading up to our filename
         while tb[0][0] != _MODULE_FILENAME:
             tb.pop(0)
         # pop frame with our filename, this should leave only TDL-code frames
         tb.pop(0)
         ns.AddError(exc, tb, error_limit=None)
         msg = "TDL job '" + name + "' failed"
         self._error_window.set_errors(ns.GetErrors(), message=msg)
         self.emit(PYSIGNAL("showEditor()"), self)
         busy = None
Пример #11
0
 def _reset_errors(self, nerr):
     """helper method, resets error markers and such. Usually tied to a hasErrors() signal
 from an error window"""
     if not self._enabled:
         return
     self._error_at_line = {}
     self._error_selections = []
     self._current_error_selection = QTextEdit.ExtraSelection()
     nerr_local = 0
     if nerr:
         error_locations = self._error_window.get_error_locations()
         for err_num, filename, line, column, suberror in error_locations:
             if filename == self._filename:
                 nerr_local += 1
                 # make cursor corresponding to line containing the error
                 cursor = QTextCursor(self._find_block_by_linenumber(line))
                 cursor.select(QTextCursor.LineUnderCursor)
                 # make selection object
                 qsel = QTextEdit.ExtraSelection()
                 qsel.cursor = cursor
                 if suberror:
                     qsel.format = self._format_suberror
                 else:
                     qsel.format = self._format_error
                 # insert into error_at_line list
                 self._error_at_line[line - 1] = len(
                     self._error_selections), cursor
                 # append to list of error selections
                 self._error_selections.append(qsel)
         self._editor.setExtraSelections(self._error_selections)
     else:
         self._editor.setExtraSelections([])
     self.emit(PYSIGNAL("hasErrors()"), self, nerr_local)
Пример #12
0
 def _compile_main_file(self):
     # self._tb_opts.setOn(False);
     self.clear_errors()
     if self._document.isModified():
         self._save_file()
     self.emit(PYSIGNAL("compileFile()"), self, self._mainfile
               or self._filename)
Пример #13
0
 def _save_profile(self, name):
     if self.profiles.has_section(name):
         if QMessageBox.warning(
                 self, "Overwriting profile", """<P>Do you really want to
                       overwrite the existing profile '%s'?</P>""" % name,
                 QMessageBox.Ok | QMessageBox.Cancel,
                 QMessageBox.Ok) != QMessageBox.Ok:
             return
         newprof = False
     else:
         self.profiles.add_section(name)
         newprof = True
     TDLOptions.save_to_config(self.profiles, name)
     try:
         ff = file(PROFILE_FILE, "wt")
         for section in sorted(self.profiles.sections()):
             ff.write("[%s]\n" % section)
             for opt, value in sorted(self.profiles.items(section)):
                 ff.write("%s = %s\n" % (opt.lower(), value))
             ff.write("\n")
         ff.close()
     except:
         dprintf(0, "error writing %s" % PROFILE_FILE)
         traceback.print_exc()
         QMessageBox.warning(
             self, "Error saving profile",
             """<P>There was an error writing to the %s file,
                        profile was not saved.</P>""" % PROFILE_FILE)
     if newprof:
         self.emit(PYSIGNAL("refreshProfiles()"))
Пример #14
0
 def load_file(self, filename, text=None, readonly=False, mainfile=None):
     """loads editor content.
 filename is filename. text is file contents, if none then file will be re-read.
 readonly is True for readonly mode.
 If mainfile is not None, then this editor is "slaved" to the mainfile. This is the
 case for files included from other modules.
 """
     self.clear_message()
     if not os.access(filename, os.W_OK):
         readonly = True
     # load text from file if not supplied
     if text is None:
         text = open(filename).read()
     self._filename = filename
     # sets as as the mainfile or as a submodule of a main file
     self._set_mainfile(mainfile)
     # set save icons, etc.
     self._qa_revert.setEnabled(True)
     self._basename = os.path.basename(filename)
     self._readonly = readonly
     self._file_disktime = filename and _file_mod_time(filename)
     self._document.setPlainText(text)
     self._document.setModified(False)
     self._editor.setReadOnly(not os.access(self._filename, os.W_OK))
     self._text_modified(False)
     # to reset labels
     QApplication.processEvents(QEventLoop.ExcludeUserInputEvents)
     # emit signals
     self.emit(PYSIGNAL("fileLoaded()"), self, filename)
     # if module is a main-level file (i.e. not slaved to another mainfile),
     # pre-import it so that compile-time menus become available
     self._tdlmod = None
     if not mainfile:
         self.import_content()
Пример #15
0
 def __init__(self, gw, dataitem, cellspec={}, default_open=None, **opts):
     browsers.GriddedPlugin.__init__(self, gw, dataitem, cellspec=cellspec)
     self._wedit = TDLEditor(self.wparent())
     self.set_widgets(self.wtop(), dataitem.caption, icon=self.icon())
     if dataitem.data is not None:
         self.set_data(dataitem)
     QObject.connect(self.wtop(), PYSIGNAL("fontChanged()"),
                     self.wtop().adjust_editor_font)
Пример #16
0
 def __init__(self,
              gw,
              parent_widget,
              max_nx=5,
              max_ny=5,
              fixed_cells=False):
     self._topgrid = QSplitter(Qt.Vertical, parent_widget)
     self._gw = gw
     self.max_nx = max_nx
     self.max_ny = max_ny
     self.max_items = max_nx * max_ny
     self._rows = []
     self._frag_tag = None
     self._pagename = self._autoname = ''
     self._icon = QIcon()
     self._icon_cou = False
     # possible layout formats (nrow,ncol)
     self._layouts = [(1, 1)]
     for i in range(2, self.max_nx + 1):
         self._layouts += [(i, i - 1), (i, i)]
     # create cells matrix
     for irow in range(self.max_ny):
         row = self.GridRow(self._topgrid)
         row.hide()
         self._rows.append(row)
         for icol in range(self.max_nx):
             pos = (self, irow, icol)
             cell = Timba.Grid.Cell(row,
                                    pos,
                                    fixed_cell=fixed_cells,
                                    page=self)
             row._cells.append(cell)
             cell._clear_slot = curry(self._clear_cell, cell)
             QWidget.connect(cell.wtop(), PYSIGNAL("closed()"),
                             cell._clear_slot)
             cell._drop_slot = curry(self.drop_cell_item, cell)
             QWidget.connect(cell.wtop(), PYSIGNAL("itemDropped()"),
                             cell._drop_slot)
             cell._cv_slot = curry(self.change_viewer, cell)
             QWidget.connect(cell.wtop(), PYSIGNAL("changeViewer()"),
                             cell._cv_slot)
             # cell._display_slot = curry(self._display_data_item,parent=weakref.ref(cell));
             # QWidget.connect(cell.wtop(),PYSIGNAL("displayDataItem()"),
             #                cell._display_slot);
     # prepare layout
     self.set_layout(0)
Пример #17
0
 def visQAction (self,parent=None):
   try: return self._qa_vis;
   except AttributeError: pass;
   qa = self._qa_vis = QAction(self.icon,"Show/hide "+self.name,parent);
   qa.setCheckable(True);
   qa.setChecked(self.isVisible());
   QObject.connect(qa,SIGNAL("triggered(bool)"),self.setVisible);
   QObject.connect(self,PYSIGNAL("visible()"),qa.setChecked);
   return qa;
Пример #18
0
 def set_errors(self,
                error_list,
                emit_signal=True,
                show_item=True,
                message="TDL compile failed"):
     """Shows an error list. errlist should be a sequence of Exception
 objects following the TDL error convention.
 message is a status message
 If show_item=True, highlights the first error
 If emit_signal=True, emits a hasErrors(nerr) pysignal
 """
     _dprint(1, "set_errors: list of", len(error_list), "entries")
     _dprint(1, "current list has", len(self._error_list), "entries")
     # do nothing if already set
     if self._error_list is error_list:
         return
     self.clear_errors(emit_signal=False)
     self._error_list = error_list
     self._error_locations = []
     # list of error locations
     self._error_items = []
     self._toplevel_error_items = []
     if error_list:
         self._populate_error_list(self._werrlist,
                                   error_list,
                                   toplevel=True)
         nerr = len(self._toplevel_error_items)
         self._error_count_label.setText('%s: <b>%d</b> errors' %
                                         (message, nerr))
         self.setWindowTitle("TDL Errors: %d" % nerr)
         if emit_signal:
             self.emit(PYSIGNAL("hasErrors"), nerr)
         if show_item:
             self._show_error_item(self._toplevel_error_items[0])
         self.show()
         # self._highlight_error(0);
         # disable run control until something gets modified
         # self._qa_run.setVisible(False);
     else:
         if emit_signal:
             self.emit(PYSIGNAL("hasErrors"), 0)
         self.setWindowTitle("TDL Errors")
         self.hide()
Пример #19
0
 def clear_errors(self, emit_signal=True):
     """clears the error list. If emit_signal=True, emits a hasErrors(0) pysignal"""
     if emit_signal:
         self.emit(PYSIGNAL("hasErrors"), 0)
     self._error_items = self._toplevel_error_items = None
     self.setWindowTitle("TDL Errors")
     self._werrlist.clear()
     self._error_count_label.setText('')
     self._error_list = []
     self._error_locations = []
     self._item_shown = None
     self.hide()
Пример #20
0
 def _highlight_error_item(self, item, emit_signal=True):
     """highlights the given error item. If emit_signal=True, emits a
 showError(index,filename,line,column) or showError(None) pysignal.
 """
     if item:
         self.show()
         toplevel_index = item._toplevel_index
         self._qa_prev_err.setEnabled(toplevel_index > 0)
         self._qa_next_err.setEnabled(
             toplevel_index < len(self._toplevel_error_items) - 1)
         # does item contain a location attribute?
         errloc = getattr(item, '_err_location', None)
         if errloc:
             # indicate location
             _dprint(1, "highlighting error in", errloc)
             if emit_signal:
                 self.emit(PYSIGNAL("showError"), *errloc)
             return
     # if we fell through to here, then no error has been shown -- emit appropriate signal
     if emit_signal:
         self.emit(PYSIGNAL("showError"), None, None, None, None)
Пример #21
0
 def __init__ (self,panel,parent):
   QToolButton.__init__(self,parent);
   self._panel = panel;
   self._label = [ "("+panel.shortname+")",panel.shortname+" " ];
   self.setIcon(panel.icon);
   self.setText(self._label[int(panel.isVisible())]);
   self.setToolButtonStyle(Qt.ToolButtonTextBesideIcon);
   self.setToolTip("Show "+panel.name);
   QObject.connect(self,SIGNAL("clicked()"),self._toggle);
   QObject.connect(panel,PYSIGNAL("visible()"),self._show_panel);
   self._default_palette = self.palette();
   self._flash_palette   = QPalette(self.palette());
   self._flash_palette.setBrush(QPalette.Background,QBrush(QColor("yellow")));
Пример #22
0
 def _save_file(self, filename=None, text=None, force=False, save_as=False):
     """Saves text. If force=False, checks modification times in case
 the file has been modified by another program.
 If force=True, saves unconditionally.
 If no filename is known, asks for one.
 Returns True if file was successfully saved, else None."""
     filename = filename or self._filename
     if filename and not save_as:
         if not force:
             if not self.sync_external_file(filename=filename, ask=True):
                 return None
     else:  # no filename, ask for one
         try:
             dialog = self._save_as_dialog
             dialog.setDirectory(dialog.directory())
             # hopefully this rescan the directory
         except AttributeError:
             self._save_as_dialog = dialog = QFileDialog(
                 self, "Saved TDL Script")
             dialog.resize(800, dialog.height())
             dialog.setMode(QFileDialog.AnyFile)
             dialog.setNameFilters(
                 ["TDL scripts (*.tdl *.py)", "All files (*.*)"])
             dialog.setViewMode(QFileDialog.Detail)
         if dialog.exec_() != QDialog.Accepted:
             return None
         filename = str(dialog.selectedFiles()[0])
     # save the file
     if text is None:
         text = str(self._editor.document().toPlainText())
     try:
         outfile = open(filename, "w").write(text)
     except IOError:
         (exctype, excvalue, tb) = sys.exc_info()
         _dprint(0, 'exception', sys.exc_info(), 'saving TDL file',
                 filename)
         self.show_message("""<b>Error writing <tt>%s</tt>:
     <i>%s (%s)</i></b>""" % (filename, excvalue, exctype.__name__),
                           error=True,
                           transient=True)
         return None
     # saved successfully, update stuff
     self._filename = filename
     self._qa_revert.setEnabled(True)
     self._basename = os.path.basename(filename)
     self._file_disktime = _file_mod_time(filename)
     self._document.setModified(False)
     self.emit(PYSIGNAL("fileSaved()"), self, filename)
     return self._filename
Пример #23
0
 def __init__(self, name, parent, menu=None, load=None, gui_parent=None):
     """Creates a folder of bookmarks, and the associated menu.
 If 'menu' is not None, bookmarks will be added to the supplied menu, else a new one will be created.
 If load is set to a list (of bookmarks records), folder will be loaded.
 'parent' is parent object. 'gui_parent' is parent object for menus (or else 'parent' will be used.)
 """
     QObject.__init__(self, parent)
     self.name = name
     self._gui_parent = gui_parent
     self._bklist = []
     self._qas = []
     if menu:
         self._menu = menu
         self._have_initial_menu = True
     else:
         self._menu = QMenu(str(name), gui_parent or parent)
         self._menu.setIcon(self.icon())
         self._have_initial_menu = False
     if load is not None:
         self.load(load)
     QObject.connect(self, PYSIGNAL("showBookmark()"), self.parent(),
                     PYSIGNAL("showBookmark()"))
     QObject.connect(self, PYSIGNAL("showPagemark()"), self.parent(),
                     PYSIGNAL("showPagemark()"))
Пример #24
0
 def get_context_menu(self):
     try:
         menu = self._context_menu
     except AttributeError:
         # create menu on the fly when first called for this item
         viewer_list = self._content is not None and self._viewable and \
                    Grid.Services.getViewerList(self._content,self._udi)
         # create menu
         menu = self._context_menu = QMenu(self.treeWidget())
         menu._callbacks = []
         menu.addAction(self._desc or self._name
                        or str(self.text(0))).setSeparator(True)
         # insert Copy item
         copy_qa = menu.addAction(pixmaps.editcopy.icon(),
                                  '&Copy to clipboard',
                                  self.copy_to_clipboard,
                                  Qt.CTRL + Qt.Key_Insert)
         # create "Precision" submenu
         if self._strfunc:
             self._prec_menu = PrecisionPopupMenu(menu, prec=self._prec)
             qa = menu.addMenu(self._prec_menu)
             qa.setText('Number format')
             qa.setIcon(pixmaps.precplus.icon())
             QWidget.connect(self._prec_menu,
                             PYSIGNAL("setPrecision()"),
                             self._set_prec_frommenu)
         # create "display with" entries
         if viewer_list:
             # create display submenus
             menu1 = self._display_menu1 = menu.addMenu(
                 pixmaps.viewmag.icon(), "Display with")
             menu2 = self._display_menu2 = menu.addMenu(
                 pixmaps.viewmag_plus.icon(), "New display with")
             for v in viewer_list:
                 # create entry for viewer
                 name = getattr(v, 'viewer_name', v.__name__)
                 try:
                     icon = v.icon()
                 except AttributeError:
                     icon = QIcon()
                 # add entry to both menus ("Display with" and "New display with")
                 menu1.addAction(icon,name, \
                   self.xcurry(self.emit_display_signal,viewer=v,_argslice=slice(0)))
                 menu2.addAction(icon,name, \
                   self.xcurry(self.emit_display_signal,viewer=v,newcell=True,_argslice=slice(0)))
     # set the precision submenu to the right setting
     return menu
Пример #25
0
    def __init__(self,
                 app,
                 verbose=0,
                 size=(500, 500),
                 poll_app=None,
                 *args,
                 **kwargs):
        """create and populate the main application window"""
        global gui
        gui = self
        #------ starts the main app object and event thread, if not already started
        self._qapp = mainapp()
        #------ init base classes
        verbosity.__init__(self, verbose, name=app.name() + "/gui")
        _dprint(1, "initializing")
        QMainWindow.__init__(self, *args)
        self.app = app
        self._connected = False

        self.populate(size=size, *args, **kwargs)

        #------ set size
        self.setCentralWidget(self.splitter)
        sz = self.size().expandedTo(QSize(size[0], size[1]))
        self.resize(sz)

        # events from remote application are emitted as PYSIGNALS taking
        # two arguments. Connect some standard handlers here
        #QObject.connect(self,PYSIGNAL("hello"),self._attached_server_event);
        #QObject.connect(self,PYSIGNAL("hello"),self.xcurry(self._update_app_state));
        #QObject.connect(self,PYSIGNAL("bye"),self._detached_server_event);
        #QObject.connect(self,PYSIGNAL("bye"),self.xcurry(self._update_app_state));
        QObject.connect(self, PYSIGNAL("app.notify.state"),
                        self.xcurry(self._update_app_state))

        #------ start timer when in polling mode
        if poll_app:
            self.startTimer(poll_app)

        global splash_screen
        if splash_screen is not None:
            splash_screen.finish(self)

        _dprint(2, "init complete")        \
Пример #26
0
 def set_widgets(self,
                 widgets,
                 captions=None,
                 icon=None,
                 enable_viewers=True):
     """Sets widget contents. Should only be called once.
 widgets:    a sequence of one widget per cell, counting across 
             the block, then down. If only a 1x1 block is allocated, 
             content may be a single widget.
 captions:   is an list of captions of the same size as widgets.
             If None is supplied, the dataitem caption is used instead.
 enable_viewers: if False, certain GUI functions will be disabled
 """
     if isinstance(widgets, QWidget):
         if len(self._cells) != 1:
             raise ValueError(
                 "len of widgets argument does not match cell layout")
         widgets = (widgets, )
     else:
         try:
             n = len(widgets)
         except:
             raise TypeError(
                 "widgets argument must be a QWidget or a list of QWidgets")
         if len(widgets) != len(self._cells):
             raise ValueError(
                 "len of widgets argument does not match cell layout")
     self._content = widgets
     self._icon = icon
     if captions is None:
         self._captions = getattr(self._dataitem, 'caption',
                                  self._dataitem.udi)
     else:
         self._captions = captions
     _dprint(2, id(self), ': set content', widgets)
     # initialize cells with contents
     self._init_cells(self._cells, enable_viewers=enable_viewers)
     # connect displayDataItem() signal from contents
     for w in widgets:
         QWidget.connect(w, PYSIGNAL("displayDataItem()"),
                         self._display_sub_item)
Пример #27
0
 def connect_app_signals(self, app):
     """connects standard app signals to appropriate methods."""
     self._app = app
     QObject.connect(app, PYSIGNAL("vis.channel.open"),
                     self.xcurry(self.start, _argslice=slice(1, 2)))
     QObject.connect(app, PYSIGNAL("vis.header"),
                     self.xcurry(self.header, _argslice=slice(1, 2)))
     QObject.connect(app, PYSIGNAL("vis.num.tiles"),
                     self.xcurry(self.update, _argslice=slice(1, 2)))
     QObject.connect(app, PYSIGNAL("vis.footer"),
                     self.xcurry(self.footer, _argslice=slice(1, 2)))
     QObject.connect(app, PYSIGNAL("vis.channel.closed"),
                     self.xcurry(self.close, _argslice=slice(1, 2)))
     QObject.connect(app, PYSIGNAL("isConnected()"),
                     self.xcurry(self.reset))
Пример #28
0
 def _text_modified(self, mod=True):
     self._modified = mod
     self.emit(PYSIGNAL("textModified()"), self, bool(mod))
     self._tb_save.setAutoRaise(not mod)
     self._qa_revert.setEnabled(mod)
     #if mod:
     #self._tb_save.setBackgroundRole(QPalette.ToolTipBase);
     #else:
     #self._tb_save.setBackgroundRole(QPalette.Button);
     if self._filename:
         label = '<b>' + self._basename + '</b>'
         self._pathlabel.setToolTip(self._filename)
     else:
         label = ''
         self._pathlabel.setToolTip('')
     if self._readonly:
         label = '[r/o] ' + label
     if mod:
         self._clear_transients()
         label = '[mod] ' + label
     self._pathlabel.setText(label)
Пример #29
0
def ubsubscribe_nodelist(callback):
    QObject.disconnect(nodelist, PYSIGNAL("loaded()"), callback)
Пример #30
0
def subscribe_forest_state(callback):
    """Adds a subscriber to node state changes. Callback must take one 
  argument: the new forest state"""
    global _forest_state_obj
    QObject.connect(_forest_state_obj, PYSIGNAL("state()"), callback)