Exemple #1
0
    def OnInit(self):
        self.log = Log()
        self.working = False
        wx.InitAllImageHandlers()
        self.andyapptitle = "ogl scroll testPyNsource GUI - Python Code into UML"

        self.frame = wx.Frame(
            None,
            -1,
            self.andyapptitle,
            pos=(50, 50),
            size=(0, 0),
            style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.DEFAULT_FRAME_STYLE,
        )
        self.frame.CreateStatusBar()

        self.umlwin = UmlCanvas(self.frame, Log(), self.frame)

        ogl.OGLInitialize()  # creates some pens and brushes that the OGL library uses.

        # Set the frame to a good size for showing stuff
        self.frame.SetSize(WINDOW_SIZE)
        self.umlwin.SetFocus()
        self.SetTopWindow(self.frame)

        self.frame.Show(True)
        wx.EVT_CLOSE(self.frame, self.OnCloseFrame)

        wx.CallAfter(self.BootStrap)  # doesn't make a difference calling this via CallAfter

        return True
Exemple #2
0
def runTest(frame, nb, log):
    # This creates some pens and brushes that the OGL library uses.
    # It should be called after the app object has been created, but
    # before OGL is used.
    ogl.OGLInitialize()

    win = TestWindow(nb, log, frame)
    return win
Exemple #3
0
    def __init__(self, parent):
        self._init_ctrls(parent)
        self.CreateToolBar()
        ogl.OGLInitialize()
        self.SetGetText()

        self.dataToSave = False
        self.designWindow = DesignWindow(self)
Exemple #4
0
    def __init__(self, *a, **k):
        super(CallGraph, self).__init__(*a, **k)
        ogl.OGLInitialize()
        vbox = wx.BoxSizer(wx.VERTICAL)
        self.canvas = MyCanvas(self)

        vbox.Add(self.canvas, 1, wx.GROW)
        self.SetSizer(vbox)
    def __init__(self,
                 parent,
                 id=-1,
                 component=None,
                 logType=0,
                 evalSpace=None,
                 bCounter=False,
                 progressDlg=None):
        """
        Конструктор базового класса пользовательских компонентов.

        @type parent: C{wx.Window}
        @param parent: Указатель на родительское окно.
        @type id: C{int}
        @param id: Идентификатор окна.
        @type component: C{dictionary}
        @param component: Словарь описания компонента.
        @type logType: C{int}
        @param logType: Тип лога (0 - консоль, 1- файл, 2- окно лога).
        @param evalSpace: Пространство имен, необходимых для вычисления внешних выражений.
        @type evalSpace: C{dictionary}
        @type bCounter: C{bool}
        @param bCounter: Признак отображения в ProgressBar-е. Иногда это не нужно -
            для создания объектов полученных по ссылки. Т. к. они не учтены при подсчете
            общего количества объектов.
        @type progressDlg: C{wx.ProgressDialog}
        @param progressDlg: Указатель на идикатор создания формы.
        """
        # Сначала инициализировать OGL если надо
        if not self.is_ogl_initialized:
            parentModule.OGLInitialize()
            self.is_ogl_initialized = True

        component = util.icSpcDefStruct(self.component_spc, component)
        icwidget.icWidget.__init__(self, parent, id, component, logType,
                                   evalSpace)

        parentModule.ShapeCanvas.__init__(self, parent, id, style=wx.NO_BORDER)
        maxWidth = 1500
        maxHeight = 1500
        self.SetScrollbars(20, 20, maxWidth / 20, maxHeight / 20)
        # --- Свойства компонента ---
        #   По спецификации создаем соответствующие атрибуты (кроме служебных атрибутов)
        lst_keys = [x for x in component.keys() if x.find('__') != 0]

        for key in lst_keys:
            setattr(self, key, component[key])

        if component.get('backgroundColor', None):
            self.SetBackgroundColour(component['backgroundColor'])

        # Инициализация внутренних объектов компонента и установка значений по умолчанию.
        self._init_ogl_default()
        self._default_par = {}

        # Текущая выделенная фигура
        self.selected_shape = None
Exemple #6
0
    def test_lib_oglEllipseShape(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.EllipseShape(50, 50)
        aShape.SetCanvas(osc)
        self.diagram.AddShape(aShape)
Exemple #7
0
def main():
    # application = MainApp(0)
    # # application = MainApp(redirect=True, filename='/tmp/pynsource.log')  # to view what's going on
    # application.MainLoop()

    app = wx.PySimpleApp()
    ogl.OGLInitialize()
    frame = AppFrame()
    app.MainLoop()
    app.Destroy()
Exemple #8
0
    def test_lib_oglCtor(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.RectangleShape(w=50, h=50)
        aShape.SetCanvas(osc)
        self.diagram.AddShape(aShape)
Exemple #9
0
    def test_lib_oglTextShape(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.TextShape(50, 50)
        aShape.SetCanvas(osc)
        aShape.AddText("Some nice text here")
        self.diagram.AddShape(aShape)
    def __init__(self, frame):
        ogl.OGLInitialize()
        ogl.ShapeCanvas.__init__(self, frame)

        maxWidth = 10000
        maxHeight = 10000
        self.SetScrollbars(20, 20, maxWidth / 20, maxHeight / 20)

        self.nodeShapes = {}
        self.connShapes = []  #Connection line shapes
        self.linesFrom = {}
        self.linesTo = {}

        self.viewMode = 'static'

        self.SetBackgroundColour(wx.Color(*Config.backgroundColorStatic))
        self.diagram = ogl.Diagram()
        self.SetDiagram(self.diagram)
        self.diagram.SetCanvas(self)
        self.SetSize((640, 480))

        self.zoom = 1
        self.mainFrame = mf = app.mainFrame

        self.menu = \
        mf.AddMenu( _('&Canvas'),   ( mf.MenuEntry( _('&Zoom +') + '\tCtrl++', _('Zooms in'), self.OnZoomPlus, 'Art/viewmag.png' ),
                                      mf.MenuEntry( _('&Zoom -') + '\tCtrl+-', _('Zooms out'), self.OnZoomMinus, 'Art/viewmag.png' ),
                                      mf.MenuEntry( _('Zoom &100%') + '\tCtrl+*', _('Reset zoom to 100%'), self.OnZoomReset, 'Art/viewmag.png' ),
                                     )
                   )

        sb = mf.statusBar
        self.zoomStatusBarWidget = wx.StaticText(sb, -1, '100%')
        noItems = sb.GetFieldsCount()
        sb.SetFieldsCount(noItems + 1)
        sb.AddWidget(self.zoomStatusBarWidget, pos=noItems)
        newWidths = sb.GetStatusWidths()[0:-1] + [60]
        sb.SetStatusWidths(newWidths)

        self.SetDropTarget(CanvasDropTarget(self))

        louie.connect(self.OnNewNode, Events.instantiateClassFinished)
        louie.connect(self.OnDeleteNode, Events.deleteNodeFinished)
        louie.connect(self.OnChangePresenterInfo,
                      Events.changePresenterInfoFinished)
        louie.connect(self.OnChangePresenterClassInfo,
                      Events.setPresenterClassInfoFinished)
        louie.connect(self.OnNewConnection, Events.createConnectionFinished)
        louie.connect(self.OnDeleteConnection, Events.deleteConnectionFinished)
        louie.connect(self.OnSetViewMode, Events.setViewMode)
        louie.connect(self.OnChangePropertyValue, Events.changePropertyValue)
        louie.connect(self.OnDisconnected, Events.disconnected)
        louie.connect(self.OnClearCanvas, Events.resetServerWorkspaceFinished)
Exemple #11
0
    def OnInit(self):
        self.Init()  # initialize the inspection tool
        # self.log = Log()
        self.working = False
        wx.InitAllImageHandlers()
        self.andyapptitle = "PyNsource GUI - Python Code into UML"

        self.frame = wx.Frame(
            None,
            -1,
            self.andyapptitle,
            pos=(50, 50),
            size=(0, 0),
            style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.DEFAULT_FRAME_STYLE,
        )
        self.frame.CreateStatusBar()

        self.notebook = wx.Notebook(self.frame, -1)
        self.umlwin = UmlCanvas(self.notebook, None, self.frame)
        self.asciiart = wx.Panel(self.notebook, -1)
        self.notebook.AddPage(self.umlwin, "UML")
        self.notebook.AddPage(self.asciiart, "Ascii Art")
        self.multiText = wx.TextCtrl(self.asciiart,
                                     -1,
                                     "ASCII_UML_HELP_MSG",
                                     style=wx.TE_MULTILINE | wx.HSCROLL)
        bsizer = wx.BoxSizer()
        bsizer.Add(self.multiText, 1, wx.EXPAND)
        self.asciiart.SetSizerAndFit(bsizer)
        self.multiText.SetFont(
            wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False)
        )  # see http://www.wxpython.org/docs/api/wx.Font-class.html for more fonts
        # self.multiText.Bind( wx.EVT_CHAR, self.onKeyChar_Ascii_Text_window)
        # self.multiText.Bind(wx.EVT_MOUSEWHEEL, self.OnWheelZoom_ascii)

        ogl.OGLInitialize(
        )  # creates some pens and brushes that the OGL library uses.

        # import pdb; pdb.set_trace()

        # Set the frame to a good size for showing stuff
        self.frame.SetSize(WINDOW_SIZE)
        self.umlwin.SetFocus()
        self.SetTopWindow(self.frame)

        self.frame.Show(True)
        print(self.umlwin.GetSize())  # should be bigger now.  but it isn't???
        # self.frame.SetSizer(self.sizer)

        self.umlwin.InitSizeAndObjs(
        )  # Now that frame is visible and calculated, there should be sensible world coords to use
        return True
Exemple #12
0
    def OnInit(self):
        self.Init()  # initialize the inspection tool
        self.log = Log()
        self.working = False
        wx.InitAllImageHandlers()
        self.andyapptitle = "ogl scroll testPyNsource GUI - Python Code into UML"

        self.frame = wx.Frame(
            None,
            -1,
            self.andyapptitle,
            pos=(450, 450),
            size=WINDOW_SIZE,
            style=wx.NO_FULL_REPAINT_ON_RESIZE | wx.DEFAULT_FRAME_STYLE,
        )
        # wx.FULL_REPAINT_ON_RESIZE
        # wx.NO_FULL_REPAINT_ON_RESIZE
        # self.frame.CreateStatusBar()

        if USENOTEBOOK:
            self.notebook = wx.Notebook(self.frame, -1)
            self.umlwin = UmlCanvas(self.notebook, Log(), self.frame)
            self.notebook.AddPage(self.umlwin, "test")
            self.notebook.AddPage(wx.Panel(self.notebook, -1), "Ascii Art")
        else:
            self.umlwin = UmlCanvas(self.frame, Log(), self.frame)

        self.umlwin.frame = self.frame

        self.umlwin.SetScrollbars(1, 1, 1200, 800)

        ogl.OGLInitialize(
        )  # creates some pens and brushes that the OGL library uses.

        # Set the frame to a good size for showing stuff
        # self.frame.SetSize(WINDOW_SIZE)

        self.umlwin.SetFocus()
        self.SetTopWindow(self.frame)

        self.frame.Show(True)
        wx.EVT_CLOSE(self.frame, self.OnCloseFrame)
        self.Bind(wx.EVT_SIZE, self.OnResizeFrame)

        wx.CallAfter(self.BootStrap
                     )  # doesn't make a difference calling this via CallAfter

        return True
Exemple #13
0
    def test_lib_oglShapeRegion(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.RectangleShape(w=50, h=50)
        aShape.SetCanvas(osc)
        self.diagram.AddShape(aShape)

        region1 = ogl.ShapeRegion()
        region1.SetText('DividedShape')
        region1.SetProportions(0.0, 0.2)
        region1.SetFormatMode(ogl.FORMAT_CENTRE_HORIZ)
        aShape.AddRegion(region1)
Exemple #14
0
    def test_lib_oglDivisonShape(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.CompositeShape()
        aShape.SetCanvas(osc)
        self.diagram.AddShape(aShape)

        # create a division in the composite
        aShape.MakeContainer()

        # add a shape to the original division
        shape2 = ogl.RectangleShape(40, 60)
        aShape.GetDivisions()[0].AddChild(shape2)
Exemple #15
0
    def OnInit(self):
        wx.Log_SetActiveTarget(wx.LogStderr())

        self.SetAssertMode(assertMode)

        # Resolve resource locations
        ed_glob.CONFIG['CONFIG_DIR'] = self.curr_dir
        ed_glob.CONFIG['INSTALL_DIR'] = self.curr_dir
        ed_glob.CONFIG['KEYPROF_DIR'] = os.path.join(self.curr_dir, u"ekeys")
        ed_glob.CONFIG['SYSPIX_DIR'] = os.path.join(self.curr_dir, u"pixmaps")
        ed_glob.CONFIG['PLUGIN_DIR'] = os.path.join(self.curr_dir, u"plugins")
        ed_glob.CONFIG['THEME_DIR'] = os.path.join(self.curr_dir, u"pixmaps",
                                                   u"theme")
        ed_glob.CONFIG['LANG_DIR'] = os.path.join(self.curr_dir, u"locale")
        ed_glob.CONFIG['STYLES_DIR'] = os.path.join(self.curr_dir, u"styles")
        ed_glob.CONFIG['SYS_PLUGIN_DIR'] = os.path.join(
            self.curr_dir, u"plugins")
        ed_glob.CONFIG['SYS_STYLES_DIR'] = os.path.join(
            self.curr_dir, u"styles")
        ed_glob.CONFIG['TEST_DIR'] = os.path.join(self.curr_dir, u"tests",
                                                  u"syntax")
        ed_glob.CONFIG['ISLOCAL'] = True
        ed_glob.CONFIG['PROFILE_DIR'] = os.path.join(self.curr_dir,
                                                     u"profiles")
        ed_glob.CONFIG['GLOBAL_PROFILE_DIR'] = os.path.join(
            self.curr_dir, u"profiles")

        Deca.CreateWorld()

        profiler.TheProfile.Load(
            os.path.join(ed_glob.CONFIG['PROFILE_DIR'], "default.ppb"))
        profiler.TheProfile.Update()

        self._pluginmgr = plugin.PluginManager()

        self.ReloadTranslation()

        ogl.OGLInitialize()
        frame = PyAUIFrame(None, _("Sampo Framework"), size=(750, 570))
        frame.Show(True)

        self.SetTopWindow(frame)
        self.frame = frame

        return True
Exemple #16
0
 def __init__(self, parent):
     ogl.OGLInitialize()
     ogl.ShapeCanvas.__init__(self, parent)
     #self.SetBackgroundColour("LIGHT BLUE") #wx.WHITE)
     self.diagram = ogl.Diagram()
     self.SetDiagram(self.diagram)
     self.diagram.SetCanvas(self)
     self.shapes = []
     if parent.Parent:
         print_size = parent.Parent.fitting_size
     else:
         from config import print_size
     w, h = print_size
     w *= 1
     h *= 1
     self.SetVirtualSize(wx.Size(w, h))
     #self.SetScrollbars(20,20,55,40)
     self.SetScrollRate(20, 20)
Exemple #17
0
    def OnInit(self):
        self.frame = wx.Frame(None,
                              -1,
                              "test scroll drawing",
                              pos=(450, 450),
                              size=WINDOW_SIZE,
                              style=wx.NO_FULL_REPAINT_ON_RESIZE
                              | wx.DEFAULT_FRAME_STYLE)
        self.shapecanvas = MyShapeCanvas(self.frame, self.frame)
        self.shapecanvas.frame = self.frame

        self.shapecanvas.SetScrollbars(1, 1, VIRTUAL_SIZE_X, VIRTUAL_SIZE_Y)

        ogl.OGLInitialize(
        )  # creates some pens and brushes that the OGL library uses.
        self.frame.Show(True)
        wx.CallAfter(self.BootStrap)
        return True
Exemple #18
0
    def __init__(self, parent, tilesize=32):
        wx.Panel.__init__(self, parent, -1)
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)
        if not TilingWindow.oglInitialized:
            ogl.OGLInitialize()
            TilingWindow.oglInitialized = True
        self.tileset = None
        self.mapWindow = ogl.ShapeCanvas(self, -1, (400, 400))
        self.sizer.Add(self.mapWindow, True, wx.EXPAND)
        self.map = ogl.Diagram()
        self.map.SetCanvas(self.mapWindow)
        self.mapWindow.SetDiagram(self.map)
        self.area = None
        self.tilelist = None
        self.mapWindow.SetBackgroundColour("LIGHT BLUE")

        self.map.SetGridSpacing(tilesize)
        self.map.SetSnapToGrid(True)

        self.map.ShowAll(True)
        self.vertSizer = wx.BoxSizer(wx.VERTICAL)
        self.tileListCtrl = wx.ListCtrl(self,
                                        style=wx.LC_REPORT | wx.LC_NO_HEADER
                                        | wx.LC_SINGLE_SEL)
        self.vertSizer.Add(self.tileListCtrl, True, wx.EXPAND)
        self.modelWindow = ModelWindow(self)
        self.modelWindow.SetSize((150, 150))
        self.vertSizer.Add(self.modelWindow, False,
                           wx.ALIGN_RIGHT | wx.ALIGN_BOTTOM)
        self.sizer.Add(self.vertSizer, False, wx.EXPAND)

        self.SetAutoLayout(True)
        self.SetSizer(self.sizer)
        self.sizer.Fit(self)

        self.Layout()
        self.Update()

        self.tilesize = tilesize
        self.tileshapes = []
        self.tileImageList = wx.ImageList(self.tilesize, self.tilesize)
        self.tileImageMap = {}
        self.tilelist = []
Exemple #19
0
    def test_lib_oglPolygonShape(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.PolygonShape()
        w, h = 60, 60
        points = [
            (0.0, -h / 2.0),
            (w / 2.0, 0.0),
            (0.0, h / 2.0),
            (-w / 2.0, 0.0),
        ]

        aShape.Create(points)
        aShape.SetCanvas(osc)
        self.diagram.AddShape(aShape)
Exemple #20
0
    def test_lib_oglLineShape(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        fromShape = ogl.RectangleShape(w=50, h=50)
        fromShape.SetCanvas(osc)
        self.diagram.AddShape(fromShape)

        toShape = ogl.RectangleShape(w=50, h=50)
        toShape.SetCanvas(osc)
        self.diagram.AddShape(toShape)

        lShape = ogl.LineShape()
        lShape.SetCanvas(osc)
        lShape.MakeLineControlPoints(2)
        fromShape.AddLine(lShape, toShape)
        self.diagram.AddShape(lShape)
        lShape.Show(True)
Exemple #21
0
def main_async():
    # see https://github.com/sirk390/wxasync
    # application = MainApp(0)
    # loop = get_event_loop()
    # loop.run_until_complete(application.MainLoop())

    app = wx.PySimpleApp()
    ogl.OGLInitialize()
    frame = AppFrame()
    loop = get_event_loop()
    loop.run_until_complete(app.MainLoop())

    # Let's also cancel all running tasks:
    # https://stackoverflow.com/questions/37278647/fire-and-forget-python-async-await
    pending = asyncio.Task.all_tasks()
    for task in pending:
        # print("Cancelling leftover task...", task._coro.cr_code.co_name, task._state)
        task.cancel()
        # Now we should await task to execute it's cancellation.
        # Cancelled task raises asyncio.CancelledError that we can suppress:
        with suppress(asyncio.CancelledError):
            loop.run_until_complete(task)
Exemple #22
0
 def __init__(self, *args, **keyw):
     #initialize
     global INITIALIZED
     if not INITIALIZED:
         ogl.OGLInitialize()
         INITIALIZED = True
     maxWidth = 800
     maxHeight = 800
     #frame
     ogl.ShapeCanvas.__init__(self,
                              size=(maxWidth, maxHeight),
                              *args,
                              **keyw)
     self.frame = wxTopLevelFrame(self)
     self.SetScrollbars(20, 20, maxWidth / 20, maxHeight / 20)
     #Print data
     self.printSetup = False
     self.printData = wx.PrintData()
     self.printData.SetPaperId(wx.PAPER_A4)
     self.printData.SetPrintMode(wx.PRINT_MODE_PRINTER)
     #events
     self.Bind(wx.EVT_LEFT_DCLICK, self.OnPrintPreview)
     self.Bind(wx.EVT_MIDDLE_DCLICK, self.OnDoSave)
     self.Bind(wx.EVT_RIGHT_DCLICK, self.OnPrintSetup)
Exemple #23
0
    def test_lib_oglCompositeShape(self):
        ogl.OGLInitialize()
        osc = ogl.ShapeCanvas(self.frame)
        self.diagram = ogl.Diagram()
        osc.SetDiagram(self.diagram)
        self.diagram.SetCanvas(osc)

        aShape = ogl.CompositeShape()
        aShape.SetCanvas(osc)
        self.diagram.AddShape(aShape)

        constraining_shape = ogl.RectangleShape(120, 100)
        constrained_shape1 = ogl.CircleShape(50)
        constrained_shape2 = ogl.RectangleShape(80, 20)

        aShape.AddChild(constraining_shape)
        aShape.AddChild(constrained_shape1)
        aShape.AddChild(constrained_shape2)

        constraint = ogl.Constraint(ogl.CONSTRAINT_MIDALIGNED_BOTTOM,
                                    constraining_shape,
                                    [constrained_shape1, constrained_shape2])
        aShape.AddConstraint(constraint)
        aShape.Recompute()
Exemple #24
0
def Main(reinicio = False):
    '''Función principal de lanzamiento de aplicación wxPython.'''
    # Comprobamos versión de Python.
    version = sys.version_info
    if version[0] != 2:
        try:
            print("Se necesita Python 2.6 o 2.7 para lanzar vipera")
        except: pass
        return
    if version[1] < 6:
        try:
            print("Se necesita Python >= 2.6 para lanzar vipera")
        except: pass
        return
    # Por defecto el idioma en español.
    idioma = SPANISH
    # Instanciación de la aplicación wxPython.
    app = wx.PySimpleApp()
    # wxPython también en español.
    wx.Locale(wx.LANGUAGE_SPANISH)
    # Si no se reinicia hay que comprobar parámetros de entrada.
    if not reinicio:
        # Opciones de lanzamiento de la aplicación.
        if len(sys.argv) > 1:
            # Eliminamos fichero de configuración de la aplicación.
            if '-r' in sys.argv[1:]:
                try:
                    os.remove(proy_por_defecto['nfich_conf'])
                except: 
                    print u"El fichero de configuración no existe o no se puede eliminar. Continuando la carga..."
            # Iniciamos la aplicación en inglés.
            if '-en' in sys.argv[1:]:
                idioma = ENGLISH
            # Ayuda de la aplicación.
            if sys.argv[1] in ['--help', '-h', '-H', '?', '/?', '-help', '--h', '--H']:
                msj = '%s %s %s%s%s' % (proy_por_defecto['NOMBRE_APLIC'], 
                                      proy_por_defecto['VERSION'],
                                      t(proy_por_defecto['FECHA_CREACION'],idioma),  
                                      enter * 2, info)
                print msj
                sys.exit(0)
            # Mostramos licencia.
            if sys.argv[1] in ['-l', '--l', '--license', '-license']:
                print licencia
                sys.exit(0)
    # Configuración de la aplicación.
    conf_vipera_p = conf_vipera()
    try:
        conf_vipera_p.abrir_fichero()
    except:
        msj = t(u'No se puede abrir el fichero de configuración',1)
        wx.MessageBox(msj, t(u"Atención",1), wx.OK)
        del app
        return False
    datos_conf = conf_vipera_p.recuperar_datos()
    # Idioma...
    if idioma == SPANISH and datos_conf['idioma'] == 'English':
        idioma = ENGLISH
        wx.Locale(wx.LANGUAGE_ENGLISH)
    if idioma == ENGLISH and datos_conf['idioma'] == u'Español':
        idioma = ENGLISH
        wx.Locale(wx.LANGUAGE_ENGLISH)
    # Mensaje de inicio...
    mensaje = t(u"Inicializando vipera...",idioma)
    busy = PBI.PyBusyInfo(mensaje, parent=None, title=t("Un momento...",idioma))
    wx.Yield()
    # Inicializamos el OGL.
    ogl.OGLInitialize()
    # Instanciamos frontend de la aplicación.
    f1 = fp(datos_conf, idioma)
    # Mostramos el frame.
    f1.Show()
    # Eliminamos mensaje de inicio.
    del busy
    # Mostramos consejos de inicio...
    if datos_conf['activar_tips']:
        fichero = os.path.realpath(proy_por_defecto['fich_tips'])
        # Número de líneas.
        try:
            f = open(fichero,'r')
            nlineas = len(f.readlines())
            f.close()
        except: nlineas = 0
        # Número al azar entre el total de líneas.
        numero = int(random.uniform(1,nlineas))
        # Creamos mensaje de consejos.
        tp = wx.CreateFileTipProvider(os.path.realpath(fichero), numero)
        # Y lo mostramos...
        showTip = wx.ShowTip(f1, tp, True)
    else: showTip = False
    # Guardamos el cambio de estado.
    f1.conf_vipera.m_checkBox_tips.Set3StateValue(showTip)
    # Si el idioma es diferente al español habrá que cambiar en todos los widgets.
    if idioma == ENGLISH: f1.conf_vipera.m_choice_idioma.SetStringSelection('English')
    if idioma == SPANISH: f1.conf_vipera.m_choice_idioma.SetStringSelection('Español')
    # Creamos fichero de log del día.
    fichero_log = proy_por_defecto['fichero_log']
    # Redireccionamos salida y errores de la aplicación al fichero log.
    app.RedirectStdio(fichero_log)
    # ¡Y esperamos a los eventos!.
    app.MainLoop()
    # Comprobamos si hay que reiniciar la aplicación.
    if os.path.exists(proy_por_defecto['file_restart_app']):
        try:
            # Eliminamos fichero.
            os.remove(proy_por_defecto['file_restart_app'])
            # Llamamos a la función con flag de reinicio activado.
            Main(True)
        except:
            msj = t(u'No se pudo reiniciar. Elimine manualmente el fichero ', idioma) + \
                proy_por_defecto['file_restart_app']
            wx.MessageBox(msj, t(u'Atención', idioma))
            "Over an element, a double left click opens edit text dialog, "
            "and a right click opens edit properties dialog. \n"
            "Multiple element can be selected with shift left click. \n"
            "Use arrow keys or drag-and-drop to move elements.\n"
            "For further information see project webpage:")
        info.WebSite = ("http://code.google.com/p/pyfpdf/wiki/Templates",
                        "pyfpdf Google Code Project")
        info.Developers = [
            __author__,
        ]

        info.License = wordwrap(__license__, 500, wx.ClientDC(self))

        # Then we call wx.AboutBox giving it that info object
        wx.AboutBox(info)

    def except_hook(self, type, value, trace):
        import traceback
        exc = traceback.format_exception(type, value, trace)
        for e in exc:
            wx.LogError(e)
        wx.LogError('Unhandled Error: %s: %s' % (str(type), str(value)))


if __name__ == "__main__":
    app = wx.PySimpleApp()
    ogl.OGLInitialize()
    frame = AppFrame()
    app.MainLoop()
    app.Destroy()
Exemple #26
0
    def OnInit(self):
        global ACTIVEGRID_BASE_IDE
        global USE_OLD_PROJECTS
        args = sys.argv

        #init ide logger
        log_mode = logger.LOG_MODE_IDE

        # Suppress non-fatal errors that might prompt the user even in cases
        # when the error does not impact them.
        #the log will redirect to NovalIDE.exe.log when convert into windows exe with py2exe
        wx.Log_SetActiveTarget(AppLog())
        if "-h" in args or "-help" in args or "--help" in args\
            or (wx.Platform == "__WXMSW__" and "/help" in args):
            print "Usage: ActiveGridAppBuilder.py [options] [filenames]\n"
            # Mac doesn't really support multiple instances for GUI apps
            # and since we haven't got time to test this thoroughly I'm
            # disabling it for now.
            if wx.Platform != "__WXMAC__":
                print "    option " + printArg(
                    "multiple"
                ) + " to allow multiple instances of application."
            print "    option " + printArg("debug") + " for debug mode."
            print "    option '-h' or " + printArg(
                "help") + " to show usage information for command."
            print "    option " + printArg("baseide") + " for base IDE mode."
            print "    [filenames] is an optional list of files you want to open when application starts."
            return False
        elif isInArgs("dev", args):
            self.SetAppName(_("NovalBuilderDev"))
            self.SetDebug(False)
        elif isInArgs("debug", args):
            self.SetAppName(_("NovalBuilderDebug"))
            self.SetDebug(True)
            ACTIVEGRID_BASE_IDE = True
            log_mode = logger.LOG_MODE_TESTRUN
            self.SetSingleInstance(False)
        elif isInArgs("baseide", args):
            self.SetAppName(_("NovalIDE"))
            ACTIVEGRID_BASE_IDE = True
        elif isInArgs("tools", args):
            USE_OLD_PROJECTS = True
        else:
            self.SetAppName(_("NovalBuilder"))
            self.SetDebug(False)
        if isInArgs("multiple", args) and wx.Platform != "__WXMAC__":
            self.SetSingleInstance(False)

        logger.initLogging(log_mode)

        if not wx.lib.pydocview.DocApp.OnInit(self):
            return False

        self.ShowSplash(getIDESplashBitmap())

        import STCTextEditor
        import TextService
        import FindInDirService
        import MarkerService
        import project as projectlib
        import ProjectEditor
        import PythonEditor
        import OutlineService
        import XmlEditor
        import HtmlEditor
        import TabbedView
        import MessageService
        ##  import OutputService
        import Service
        import ImageEditor
        import PerlEditor
        import PHPEditor
        import wx.lib.ogl as ogl
        import DebuggerService
        import AboutDialog
        import SVNService
        import ExtensionService
        import CompletionService
        import GeneralOption
        import NavigationService
        import TabbedFrame
        ##        import UpdateLogIniService

        _EDIT_LAYOUTS = True
        self._open_project_path = None

        # This creates some pens and brushes that the OGL library uses.
        # It should be called after the app object has been created, but
        # before OGL is used.
        ogl.OGLInitialize()

        config = wx.Config(self.GetAppName(), style=wx.CONFIG_USE_LOCAL_FILE)
        if not config.Exists(
                "MDIFrameMaximized"
        ):  # Make the initial MDI frame maximize as default
            config.WriteInt("MDIFrameMaximized", True)
        if not config.Exists(
                "MDIEmbedRightVisible"
        ):  # Make the properties embedded window hidden as default
            config.WriteInt("MDIEmbedRightVisible", False)

        ##my_locale must be set as app member property,otherwise it will only workable when app start up
        ##it will not workable after app start up,the translation also will not work
        lang_id = GeneralOption.GetLangId(config.Read("Language", ""))
        if wx.Locale.IsAvailable(lang_id):
            self.my_locale = wx.Locale(lang_id)
            if self.my_locale.IsOk():
                self.my_locale.AddCatalogLookupPathPrefix(
                    os.path.join(sysutilslib.mainModuleDir, 'noval', 'locale'))
                ibRet = self.my_locale.AddCatalog(self.GetAppName().lower())
                ibRet = self.my_locale.AddCatalog("wxstd")
                self.my_locale.AddCatalog("wxstock")

        docManager = IDEDocManager(flags=self.GetDefaultDocManagerFlags())
        self.SetDocumentManager(docManager)

        # Note:  These templates must be initialized in display order for the "Files of type" dropdown for the "File | Open..." dialog
        defaultTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Any"),
            "*.*",
            _("Any"),
            _(".txt"),
            _("Text Document"),
            _("Text View"),
            STCTextEditor.TextDocument,
            STCTextEditor.TextView,
            wx.lib.docview.TEMPLATE_INVISIBLE,
            icon=STCTextEditor.getTextIcon())
        docManager.AssociateTemplate(defaultTemplate)

        htmlTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("HTML"),
            "*.html;*.htm",
            _("HTML"),
            _(".html"),
            _("HTML Document"),
            _("HTML View"),
            HtmlEditor.HtmlDocument,
            HtmlEditor.HtmlView,
            icon=HtmlEditor.getHTMLIcon())
        docManager.AssociateTemplate(htmlTemplate)

        imageTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Image"),
            "*.bmp;*.ico;*.gif;*.jpg;*.jpeg;*.png",
            _("Image"),
            _(".png"),
            _("Image Document"),
            _("Image View"),
            ImageEditor.ImageDocument,
            ImageEditor.ImageView,
            wx.lib.docview.TEMPLATE_NO_CREATE,
            icon=ImageEditor.getImageIcon())
        docManager.AssociateTemplate(imageTemplate)

        perlTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Perl"),
            "*.pl",
            _("Perl"),
            _(".pl"),
            _("Perl Document"),
            _("Perl View"),
            PerlEditor.PerlDocument,
            PerlEditor.PerlView,
            icon=PerlEditor.getPerlIcon())
        docManager.AssociateTemplate(perlTemplate)

        phpTemplate = wx.lib.docview.DocTemplate(docManager,
                                                 _("PHP"),
                                                 "*.php",
                                                 _("PHP"),
                                                 _(".php"),
                                                 _("PHP Document"),
                                                 _("PHP View"),
                                                 PHPEditor.PHPDocument,
                                                 PHPEditor.PHPView,
                                                 icon=PHPEditor.getPHPIcon())
        docManager.AssociateTemplate(phpTemplate)

        projectTemplate = ProjectEditor.ProjectTemplate(
            docManager,
            _("Project"),
            "*%s" % PROJECT_EXTENSION,
            _("Project"),
            _(PROJECT_EXTENSION),
            _("Project Document"),
            _("Project View"),
            ProjectEditor.ProjectDocument,
            ProjectEditor.ProjectView,
            ###   wx.lib.docview.TEMPLATE_NO_CREATE,
            icon=ProjectEditor.getProjectIcon())
        docManager.AssociateTemplate(projectTemplate)

        pythonTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Python"),
            "*.py;*.pyw",
            _("Python"),
            _(".py"),
            _("Python Document"),
            _("Python View"),
            PythonEditor.PythonDocument,
            PythonEditor.PythonView,
            icon=PythonEditor.getPythonIcon())
        docManager.AssociateTemplate(pythonTemplate)

        textTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Text"),
            "*.text;*.txt",
            _("Text"),
            _(".txt"),
            _("Text Document"),
            _("Text View"),
            STCTextEditor.TextDocument,
            STCTextEditor.TextView,
            icon=STCTextEditor.getTextIcon())
        docManager.AssociateTemplate(textTemplate)

        xmlTemplate = wx.lib.docview.DocTemplate(docManager,
                                                 _("XML"),
                                                 "*.xml",
                                                 _("XML"),
                                                 _(".xml"),
                                                 _("XML Document"),
                                                 _("XML View"),
                                                 XmlEditor.XmlDocument,
                                                 XmlEditor.XmlView,
                                                 icon=XmlEditor.getXMLIcon())
        docManager.AssociateTemplate(xmlTemplate)

        pythonService = self.InstallService(
            PythonEditor.PythonService(_("Python Interpreter"),
                                       embeddedWindowLocation=wx.lib.pydocview.
                                       EMBEDDED_WINDOW_BOTTOM))
        if not ACTIVEGRID_BASE_IDE:
            propertyService = self.InstallService(
                PropertyService.PropertyService(
                    "Properties",
                    embeddedWindowLocation=wx.lib.pydocview.
                    EMBEDDED_WINDOW_RIGHT))
        projectService = self.InstallService(
            ProjectEditor.ProjectService(_("Projects/Resources View"),
                                         embeddedWindowLocation=wx.lib.
                                         pydocview.EMBEDDED_WINDOW_TOPLEFT))
        findService = self.InstallService(FindInDirService.FindInDirService())
        if not ACTIVEGRID_BASE_IDE:
            webBrowserService = self.InstallService(
                WebBrowserService.WebBrowserService()
            )  # this must be before webServerService since it sets the proxy environment variable that is needed by the webServerService.
            webServerService = self.InstallService(
                WebServerService.WebServerService()
            )  # this must be after webBrowserService since that service sets the proxy environment variables.
        outlineService = self.InstallService(
            OutlineService.OutlineService(
                _("Outline"),
                embeddedWindowLocation=wx.lib.pydocview.
                EMBEDDED_WINDOW_BOTTOMLEFT))
        filePropertiesService = self.InstallService(
            wx.lib.pydocview.FilePropertiesService())
        markerService = self.InstallService(MarkerService.MarkerService())
        textService = self.InstallService(TextService.TextService())
        perlService = self.InstallService(PerlEditor.PerlService())
        phpService = self.InstallService(PHPEditor.PHPService())
        comletionService = self.InstallService(
            CompletionService.CompletionService())
        navigationService = self.InstallService(
            NavigationService.NavigationService())
        messageService = self.InstallService(
            MessageService.MessageService(_("Search Results"),
                                          embeddedWindowLocation=wx.lib.
                                          pydocview.EMBEDDED_WINDOW_BOTTOM))
        ##    outputService          = self.InstallService(OutputService.OutputService("Output", embeddedWindowLocation = wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOM))
        debuggerService = self.InstallService(
            DebuggerService.DebuggerService("Debugger",
                                            embeddedWindowLocation=wx.lib.
                                            pydocview.EMBEDDED_WINDOW_BOTTOM))
        extensionService = self.InstallService(
            ExtensionService.ExtensionService())
        ###optionsService          = self.InstallService(wx.lib.pydocview.DocOptionsService(supportedModes=wx.lib.docview.DOC_MDI))
        optionsService = self.InstallService(
            GeneralOption.GeneralOptionsService())
        aboutService = self.InstallService(
            wx.lib.pydocview.AboutService(AboutDialog.AboutDialog))
        ###   svnService              = self.InstallService(SVNService.SVNService())
        if not ACTIVEGRID_BASE_IDE:
            helpPath = os.path.join(sysutilslib.mainModuleDir, "activegrid",
                                    "tool", "data", "AGDeveloperGuideWebHelp",
                                    "AGDeveloperGuideWebHelp.hhp")
            helpService = self.InstallService(
                HelpService.HelpService(helpPath))
        if self.GetUseTabbedMDI():
            windowService = self.InstallService(
                wx.lib.pydocview.WindowMenuService())

        # order of these added determines display order of Options Panels
        optionsService.AddOptionsPanel(ProjectEditor.ProjectOptionsPanel)
        ## optionsService.AddOptionsPanel(DebuggerService.DebuggerOptionsPanel)
        optionsService.AddOptionsPanel(PythonEditor.PythonOptionsPanel)
        ##      optionsService.AddOptionsPanel(PHPEditor.PHPOptionsPanel)
        ##    optionsService.AddOptionsPanel(PerlEditor.PerlOptionsPanel)
        optionsService.AddOptionsPanel(XmlEditor.XmlOptionsPanel)
        optionsService.AddOptionsPanel(HtmlEditor.HtmlOptionsPanel)
        optionsService.AddOptionsPanel(STCTextEditor.TextOptionsPanel)
        ##      optionsService.AddOptionsPanel(SVNService.SVNOptionsPanel)
        optionsService.AddOptionsPanel(ExtensionService.ExtensionOptionsPanel)

        filePropertiesService.AddCustomEventHandler(projectService)

        outlineService.AddViewTypeForBackgroundHandler(PythonEditor.PythonView)
        ###outlineService.AddViewTypeForBackgroundHandler(PHPEditor.PHPView)
        outlineService.AddViewTypeForBackgroundHandler(
            ProjectEditor.ProjectView
        )  # special case, don't clear outline if in project
        outlineService.AddViewTypeForBackgroundHandler(
            MessageService.MessageView
        )  # special case, don't clear outline if in message window
        if not ACTIVEGRID_BASE_IDE:
            outlineService.AddViewTypeForBackgroundHandler(
                DataModelEditor.DataModelView)
            outlineService.AddViewTypeForBackgroundHandler(
                ProcessModelEditor.ProcessModelView)
            outlineService.AddViewTypeForBackgroundHandler(
                PropertyService.PropertyView
            )  # special case, don't clear outline if in property window
        outlineService.StartBackgroundTimer()

        ##        projectService.AddLogicalViewFolderDefault(".agp", _("Projects"))
        ##        projectService.AddLogicalViewFolderDefault(".wsdlag", _("Services"))
        ##        projectService.AddLogicalViewFolderDefault(".wsdl", _("Services"))
        ##        projectService.AddLogicalViewFolderDefault(".xsd", _("Data Models"))
        ##        projectService.AddLogicalViewFolderDefault(".bpel", _("Page Flows"))
        ##        projectService.AddLogicalViewFolderDefault(".xform", _("Pages"))
        ##        projectService.AddLogicalViewFolderDefault(".xacml", _("Security"))
        ##        projectService.AddLogicalViewFolderDefault(".lyt", _("Presentation/Layouts"))
        ##        projectService.AddLogicalViewFolderDefault(".skn", _("Presentation/Skins"))
        ##        projectService.AddLogicalViewFolderDefault(".css", _("Presentation/Stylesheets"))
        ##        projectService.AddLogicalViewFolderDefault(".js", _("Presentation/Javascript"))
        ##        projectService.AddLogicalViewFolderDefault(".html", _("Presentation/Static"))
        ##        projectService.AddLogicalViewFolderDefault(".htm", _("Presentation/Static"))
        ##        projectService.AddLogicalViewFolderDefault(".gif", _("Presentation/Images"))
        ##        projectService.AddLogicalViewFolderDefault(".jpeg", _("Presentation/Images"))
        ##        projectService.AddLogicalViewFolderDefault(".jpg", _("Presentation/Images"))
        ##        projectService.AddLogicalViewFolderDefault(".png", _("Presentation/Images"))
        ##        projectService.AddLogicalViewFolderDefault(".ico", _("Presentation/Images"))
        ##        projectService.AddLogicalViewFolderDefault(".bmp", _("Presentation/Images"))
        ##        projectService.AddLogicalViewFolderDefault(".py", _("Code"))
        ##        projectService.AddLogicalViewFolderDefault(".php", _("Code"))
        ##        projectService.AddLogicalViewFolderDefault(".pl", _("Code"))
        ##        projectService.AddLogicalViewFolderDefault(".sql", _("Code"))
        ##        projectService.AddLogicalViewFolderDefault(".xml", _("Code"))
        ##        projectService.AddLogicalViewFolderDefault(".dpl", _("Code"))
        ##
        ##        projectService.AddLogicalViewFolderCollapsedDefault(_("Page Flows"), False)
        ##        projectService.AddLogicalViewFolderCollapsedDefault(_("Pages"), False)

        iconPath = os.path.join(sysutilslib.mainModuleDir, "noval", "tool",
                                "bmp_source", "noval.ico")
        self.SetDefaultIcon(wx.Icon(iconPath, wx.BITMAP_TYPE_ICO))
        if not ACTIVEGRID_BASE_IDE:
            embeddedWindows = wx.lib.pydocview.EMBEDDED_WINDOW_TOPLEFT | wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOMLEFT | wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOM | wx.lib.pydocview.EMBEDDED_WINDOW_RIGHT
        else:
            embeddedWindows = wx.lib.pydocview.EMBEDDED_WINDOW_TOPLEFT | wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOMLEFT | wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOM
        if self.GetUseTabbedMDI():
            self.frame = TabbedFrame.IDEDocTabbedParentFrame(
                docManager,
                None,
                -1,
                wx.GetApp().GetAppName(),
                embeddedWindows=embeddedWindows,
                minSize=150)
        else:
            self.frame = TabbedFrame.IDEMDIParentFrame(
                docManager,
                None,
                -1,
                wx.GetApp().GetAppName(),
                embeddedWindows=embeddedWindows,
                minSize=150)
        self.frame.Show(True)
        self.toolbar = self.frame.GetToolBar()
        self.toolbar_combox = self.toolbar.FindControl(
            DebuggerService.DebuggerService.COMBO_INTERPRETERS_ID)

        wx.lib.pydocview.DocApp.CloseSplash(self)
        self.OpenCommandLineArgs()

        if not projectService.LoadSavedProjects(
        ) and not docManager.GetDocuments() and self.IsSDI(
        ):  # Have to open something if it's SDI and there are no projects...
            projectTemplate.CreateDocument(
                '', wx.lib.docview.DOC_NEW).OnNewDocument()

        interpretermanager.InterpreterManager().LoadDefaultInterpreter()
        self.AddInterpreters()
        projectService.SetCurrentProject()
        intellisence.IntellisenceManager().generate_default_intellisence_data()

        self.ShowTipfOfDay()
        wx.CallAfter(self.CheckUpdate, extensionService)
        wx.UpdateUIEvent.SetUpdateInterval(
            1000
        )  # Overhead of updating menus was too much.  Change to update every n milliseconds.
        return True
Exemple #27
0
    def OnInit(self):
        self.Init()  # initialize the inspection tool
        self.log = Log()
        self.working = False
        wx.InitAllImageHandlers()
        self.andyapptitle = 'PyNsource GUI - Python Code into UML'

        self.frame = wx.Frame(None,
                              -1,
                              self.andyapptitle,
                              pos=(50, 50),
                              size=(0, 0),
                              style=wx.NO_FULL_REPAINT_ON_RESIZE
                              | wx.DEFAULT_FRAME_STYLE)
        self.frame.CreateStatusBar()

        if MULTI_TAB_GUI:
            self.notebook = wx.Notebook(self.frame, -1)

            if USE_SIZER:
                # create the chain of real objects
                panel = wx.Panel(self.notebook, -1)
                self.umlwin = UmlCanvas(panel, Log(), self.frame)
                # add children to sizers and set the sizer to the parent
                sizer = wx.BoxSizer(wx.VERTICAL)
                sizer.Add(self.umlwin, 1, wx.GROW)
                panel.SetSizer(sizer)
            else:
                self.umlwin = UmlCanvas(self.notebook, Log(), self.frame)

            #self.yuml = ImageViewer(self.notebook) # wx.Panel(self.notebook, -1)

            self.asciiart = wx.Panel(self.notebook, -1)

            if USE_SIZER:
                self.notebook.AddPage(panel, "UML")
            else:
                self.notebook.AddPage(self.umlwin, "UML")
            #self.notebook.AddPage(self.yuml, "yUml")
            self.notebook.AddPage(self.asciiart, "Ascii Art")

            # Modify my own page http://www.andypatterns.com/index.php/products/pynsource/asciiart/
            # Some other ideas here http://c2.com/cgi/wiki?UmlAsciiArt
            self.multiText = wx.TextCtrl(self.asciiart,
                                         -1,
                                         ASCII_UML_HELP_MSG,
                                         style=wx.TE_MULTILINE | wx.HSCROLL)
            bsizer = wx.BoxSizer()
            bsizer.Add(self.multiText, 1, wx.EXPAND)
            self.asciiart.SetSizerAndFit(bsizer)
            self.multiText.SetFont(
                wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False)
            )  # see http://www.wxpython.org/docs/api/wx.Font-class.html for more fonts
            self.multiText.Bind(wx.EVT_CHAR, self.onKeyChar_Ascii_Text_window)
            self.multiText.Bind(wx.EVT_MOUSEWHEEL, self.OnWheelZoom_ascii)

            self.notebook.Bind(wx.EVT_NOTEBOOK_PAGE_CHANGED,
                               self.OnTabPageChanged)

        else:
            self.notebook = None

            self.panel_one = wx.Panel(self.frame, -1)
            self.umlwin = UmlCanvas(self.panel_one, Log(), self.frame)
            #
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self.umlwin, 1, wx.EXPAND)
            self.panel_one.SetSizer(sizer)

            self.panel_two = self.asciiart = wx.Panel(self.frame, -1)
            self.multiText = wx.TextCtrl(self.panel_two,
                                         -1,
                                         ASCII_UML_HELP_MSG,
                                         style=wx.TE_MULTILINE | wx.HSCROLL)
            self.multiText.SetFont(
                wx.Font(10, wx.MODERN, wx.NORMAL, wx.NORMAL, False)
            )  # see http://www.wxpython.org/docs/api/wx.Font-class.html for more fonts
            self.multiText.Bind(wx.EVT_CHAR, self.onKeyChar_Ascii_Text_window)
            self.multiText.Bind(wx.EVT_MOUSEWHEEL, self.OnWheelZoom_ascii)
            #
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self.multiText, 1, wx.EXPAND)
            self.panel_two.SetSizer(sizer)

            self.panel_two.Hide()

            self.sizer = wx.BoxSizer(wx.VERTICAL)
            self.sizer.Add(self.panel_one, 1, wx.EXPAND)
            self.sizer.Add(self.panel_two, 1, wx.EXPAND)
            self.frame.SetSizer(self.sizer)

        ogl.OGLInitialize(
        )  # creates some pens and brushes that the OGL library uses.

        # Set the frame to a good size for showing stuff
        self.frame.SetSize(WINDOW_SIZE)
        self.umlwin.SetFocus()
        self.SetTopWindow(self.frame)

        self.frame.Show(
            True
        )  # in wxpython2.8 this causes umlwin canvas to grow too, but not in wxpython3 - till much later
        wx.EVT_CLOSE(self.frame, self.OnCloseFrame)

        self.popupmenu = None
        self.umlwin.Bind(
            wx.EVT_RIGHT_DOWN, self.OnRightButtonMenu
        )  # WARNING: takes over all righclick events - need to event.skip() to let through things to UmlShapeHandler
        self.Bind(wx.EVT_SIZE, self.OnResizeFrame)

        #self.umlwin.Bind(wx.EVT_SET_FOCUS, self.onFocus)  # attempt at making mousewheel auto scroll the workspace
        #self.frame.Bind(wx.EVT_SET_FOCUS, self.onFocus)   # attempt at making mousewheel auto scroll the workspace

        self.umlwin.InitSizeAndObjs(
        )  # Now that frame is visible and calculated, there should be sensible world coords to use

        self.InitConfig()

        class Context(object):
            """ Everything everybody needs to know """
            pass

        context = Context()
        # init the context
        context.wxapp = self
        context.config = self.config
        context.umlwin = self.umlwin
        context.model = self.umlwin.umlworkspace
        context.snapshot_mgr = self.umlwin.snapshot_mgr
        context.coordmapper = self.umlwin.coordmapper
        context.layouter = self.umlwin.layouter
        context.overlap_remover = self.umlwin.overlap_remover
        context.frame = self.frame
        if MULTI_TAB_GUI:
            context.multiText = self.multiText
            context.asciiart = self.asciiart
        else:
            context.multiText = None
            context.asciiart = None

        # App knows about everyone.
        # Everyone (ring classes) should be an adapter
        # but not strictly necessary unless you want an extra level
        # of indirection and separation or don't want to constantly
        # edit the ring classes to match what the app (and other ring
        # objects) expect - edit an adapter instead.
        self.app = App(context)
        self.app.Boot()

        self.InitMenus()
        self.PostOglViewSwitch()  # ensure key bindings kick in under linux

        self.frame.CenterOnScreen()

        wx.CallAfter(self.app.run.CmdBootStrap
                     )  # doesn't make a difference calling this via CallAfter
        return True
Exemple #28
0
    def __init__(self, parent=None, id=-1, title="YEI Node Graph"):
        """ Initializes the MainWindow class.
            
            Args:
                parent: A reference to another wxPython object (default is None)
                id: An integer denoting an ID for the window (default is -1)
                title: A string denoting the title of the window
                    (default is "Node Graph")
        """
        wx.Frame.__init__(self,
                          parent,
                          id,
                          title,
                          size=(800, 600),
                          style=wx.DEFAULT_FRAME_STYLE
                          | wx.NO_FULL_REPAINT_ON_RESIZE)
        self.SetMinSize((800, 600))
        if parent is not None:
            self.SetIcon(parent.GetIcon())
        else:
            self.SetIcon(
                wx.Icon(os.path.join(_dir_path, "media\\3Space_Icon.ico"),
                        wx.BITMAP_TYPE_ICO))

        ogl.OGLInitialize()
        self.script_win = NodeScriptWindow(self)
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(self.script_win, 4, wx.EXPAND)
        self.side_panel = SidePanel(self)
        self.timer_interval = None
        box.Add(self.side_panel, 0, wx.EXPAND | wx.FIXED_MINSIZE)
        self.config_win = sc.SensorConfigurationWindow(self, sc.SENS_CONF_SIZE)
        base_ng.global_config_win = self.config_win

        self.SetAutoLayout(True)
        self.SetSizer(box)
        self.Layout()

        # Binds
        if parent is None:
            self.Bind(wx.EVT_CLOSE, self.onAppClose)

        # StatusBar
        self.CreateStatusBar()

        # Filemenu
        file_menu = wx.Menu()

        # Filemenu - New
        menu_item = file_menu.Append(
            -1, "&New", "Creates a new layout for the Node Graph")
        self.Bind(wx.EVT_MENU, self.onNew, menu_item)

        # Filemenu - Separator
        file_menu.AppendSeparator()

        # Filemenu - Save
        menu_item = file_menu.Append(
            -1, "&Save", "Save the current layout of the Node Graph")
        self.Bind(wx.EVT_MENU, self.onSave, menu_item)

        # Filemenu - Load
        menu_item = file_menu.Append(
            -1, "&Load", "Loads a new layout from file into the Node Graph")
        self.Bind(wx.EVT_MENU, self.onLoad, menu_item)

        # Filemenu - Separator
        file_menu.AppendSeparator()

        # Filemenu - About
        menu_item = file_menu.Append(-1, "&About",
                                     "Information about this program")
        self.Bind(wx.EVT_MENU, self.onAbout, menu_item)

        # Filemenu - Separator
        file_menu.AppendSeparator()

        # Filemenu - Exit
        menu_item = file_menu.Append(-1, "E&xit", "Terminate the program")
        self.Bind(wx.EVT_MENU, self.onExit, menu_item)

        # 3Spacemenu
        ts_menu = wx.Menu()

        # 3Spacemenu - Find & Configure
        menu_item = ts_menu.Append(
            -1, "&Find && Configure",
            "Finds and configures the 3-Space Sensor devices")
        self.Bind(wx.EVT_MENU, self.onConfigureOpen, menu_item)

        # Menubar
        menu_bar = wx.MenuBar()
        menu_bar.Append(file_menu, "&File")
        menu_bar.Append(ts_menu, "&Device Settings")

        if parent is None:
            # Streammenu
            stream_menu = wx.Menu()

            # Streammenu - Find & Configure
            menu_item = stream_menu.AppendCheckItem(
                -1, "&Start Streaming",
                "Starts streaming data for the 3-Space Sensors")
            self.Bind(wx.EVT_MENU, self.onStream, menu_item)

            menu_bar.Append(stream_menu, "&Streaming Settings")

        self.SetMenuBar(menu_bar)
Exemple #29
0
    def OnInit(self):
        global ACTIVEGRID_BASE_IDE

        args = sys.argv

        if "-h" in args or "-help" in args or "--help" in args\
            or (wx.Platform == "__WXMSW__" and "/help" in args):
            print "Usage: ActiveGridAppBuilder.py [options] [filenames]\n"
            # Mac doesn't really support multiple instances for GUI apps
            # and since we haven't got time to test this thoroughly I'm
            # disabling it for now.
            if wx.Platform != "__WXMAC__":
                print "    option " + printArg(
                    "multiple"
                ) + " to allow multiple instances of application."
            print "    option " + printArg("debug") + " for debug mode."
            print "    option '-h' or " + printArg(
                "help") + " to show usage information for command."
            print "    option " + printArg("baseide") + " for base IDE mode."
            print "    [filenames] is an optional list of files you want to open when application starts."
            return False
        elif isInArgs("dev", args):
            self.SetAppName(_("ActiveGrid Application Builder Dev"))
            self.SetDebug(False)
        elif isInArgs("debug", args):
            self.SetAppName(_("ActiveGrid Application Builder Debug"))
            self.SetDebug(True)
            self.SetSingleInstance(False)
        elif isInArgs("baseide", args):
            self.SetAppName(_("Torque MMO Kit IDE"))
            ACTIVEGRID_BASE_IDE = True
        else:
            self.SetAppName(_("ActiveGrid Application Builder"))
            self.SetDebug(False)
        if isInArgs("multiple", args) and wx.Platform != "__WXMAC__":
            self.SetSingleInstance(False)

        if not wx.lib.pydocview.DocApp.OnInit(self):
            return False

        jpg = wx.Image('./mmoide/tool/data/splash.jpg',
                       wx.BITMAP_TYPE_JPEG).ConvertToBitmap()

        self.ShowSplash(jpg)

        import STCTextEditor
        import FindInDirService
        import MarkerService
        import project as projectlib
        import ProjectEditor
        import PythonEditor
        import OutlineService
        import TabbedView
        import MessageService
        import Service
        import wx.lib.ogl as ogl
        #import DebuggerService
        import AboutDialog
        #import SVNService
        import ExtensionService

        import ZoneService
        import WorldService
        import MMOService

        _EDIT_LAYOUTS = True

        # This creates some pens and brushes that the OGL library uses.
        # It should be called after the app object has been created, but
        # before OGL is used.
        ogl.OGLInitialize()

        config = wx.FileConfig(self.GetAppName(),
                               "MMOWorkshop.com",
                               os.getcwd() + "/projects/ideconfig.ini",
                               "",
                               style=wx.CONFIG_USE_LOCAL_FILE)
        wx.ConfigBase_Set(config)

        if not config.Exists(
                "MDIFrameMaximized"
        ):  # Make the initial MDI frame maximize as default
            config.WriteInt("MDIFrameMaximized", True)
        if not config.Exists(
                "MDIEmbedRightVisible"
        ):  # Make the properties embedded window hidden as default
            config.WriteInt("MDIEmbedRightVisible", False)

        docManager = wx.lib.docview.DocManager(
            flags=self.GetDefaultDocManagerFlags())
        self.SetDocumentManager(docManager)

        defaultTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Any"),
            "*.*",
            _("Any"),
            _(".txt"),
            _("Text Document"),
            _("Text View"),
            STCTextEditor.TextDocument,
            STCTextEditor.TextView,
            wx.lib.docview.TEMPLATE_INVISIBLE,
            icon=STCTextEditor.getTextIcon())
        docManager.AssociateTemplate(defaultTemplate)

        projectTemplate = ProjectEditor.ProjectTemplate(
            docManager,
            _("Project"),
            "*.agp",
            _("Project"),
            _(".agp"),
            _("Project Document"),
            _("Project View"),
            ProjectEditor.ProjectDocument,
            ProjectEditor.ProjectView,
            icon=ProjectEditor.getProjectIcon())
        docManager.AssociateTemplate(projectTemplate)

        pythonTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Python"),
            "*.py",
            _("Python"),
            _(".py"),
            _("Python Document"),
            _("Python View"),
            PythonEditor.PythonDocument,
            PythonEditor.PythonView,
            icon=PythonEditor.getPythonIcon())
        docManager.AssociateTemplate(pythonTemplate)

        textTemplate = wx.lib.docview.DocTemplate(
            docManager,
            _("Text"),
            "*.text;*.txt",
            _("Text"),
            _(".txt"),
            _("Text Document"),
            _("Text View"),
            STCTextEditor.TextDocument,
            STCTextEditor.TextView,
            icon=STCTextEditor.getTextIcon())
        docManager.AssociateTemplate(textTemplate)

        textService = self.InstallService(STCTextEditor.TextService())
        pythonService = self.InstallService(PythonEditor.PythonService())
        projectService = self.InstallService(
            ProjectEditor.ProjectService("Projects",
                                         embeddedWindowLocation=wx.lib.
                                         pydocview.EMBEDDED_WINDOW_TOPLEFT))
        findService = self.InstallService(FindInDirService.FindInDirService())
        outlineService = self.InstallService(
            OutlineService.OutlineService(
                "Outline",
                embeddedWindowLocation=wx.lib.pydocview.
                EMBEDDED_WINDOW_BOTTOMLEFT))
        filePropertiesService = self.InstallService(
            wx.lib.pydocview.FilePropertiesService())
        markerService = self.InstallService(MarkerService.MarkerService())
        messageService = self.InstallService(
            MessageService.MessageService("Messages",
                                          embeddedWindowLocation=wx.lib.
                                          pydocview.EMBEDDED_WINDOW_BOTTOM))
        #debuggerService         = self.InstallService(DebuggerService.DebuggerService("Debugger", embeddedWindowLocation = wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOM))
        extensionService = self.InstallService(
            ExtensionService.ExtensionService())
        optionsService = self.InstallService(
            wx.lib.pydocview.DocOptionsService(
                supportedModes=wx.lib.docview.DOC_MDI))
        aboutService = self.InstallService(
            wx.lib.pydocview.AboutService(AboutDialog.AboutDialog))
        #svnService              = self.InstallService(SVNService.SVNService())

        worldService = self.InstallService(WorldService.WorldService())
        zoneService = self.InstallService(ZoneService.ZoneService())
        mmoService = self.InstallService(MMOService.MMOService())

        # order of these added determines display order of Options Panels
        optionsService.AddOptionsPanel(ProjectEditor.ProjectOptionsPanel)
        #optionsService.AddOptionsPanel(DebuggerService.DebuggerOptionsPanel)
        optionsService.AddOptionsPanel(PythonEditor.PythonOptionsPanel)
        optionsService.AddOptionsPanel(STCTextEditor.TextOptionsPanel)
        #optionsService.AddOptionsPanel(SVNService.SVNOptionsPanel)
        optionsService.AddOptionsPanel(ExtensionService.ExtensionOptionsPanel)

        filePropertiesService.AddCustomEventHandler(projectService)

        outlineService.AddViewTypeForBackgroundHandler(PythonEditor.PythonView)
        outlineService.AddViewTypeForBackgroundHandler(
            ProjectEditor.ProjectView
        )  # special case, don't clear outline if in project
        outlineService.AddViewTypeForBackgroundHandler(
            MessageService.MessageView
        )  # special case, don't clear outline if in message window
        outlineService.StartBackgroundTimer()

        projectService.AddLogicalViewFolderDefault(".gif", _("Images"))
        projectService.AddLogicalViewFolderDefault(".jpeg", _("Images"))
        projectService.AddLogicalViewFolderDefault(".jpg", _("Images"))
        projectService.AddLogicalViewFolderDefault(".py", None)

        self.SetDefaultIcon(getActiveGridIcon())
        embeddedWindows = wx.lib.pydocview.EMBEDDED_WINDOW_TOPLEFT | wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOMLEFT | wx.lib.pydocview.EMBEDDED_WINDOW_BOTTOM
        if self.GetUseTabbedMDI():
            self.frame = IDEDocTabbedParentFrame(
                docManager,
                None,
                -1,
                wx.GetApp().GetAppName(),
                embeddedWindows=embeddedWindows)
        else:
            self.frame = IDEMDIParentFrame(docManager,
                                           None,
                                           -1,
                                           wx.GetApp().GetAppName(),
                                           embeddedWindows=embeddedWindows)
        self.frame.Show(True)

        wx.lib.pydocview.DocApp.CloseSplash(self)
        self.OpenCommandLineArgs()

        if not projectService.OpenSavedProjects(
        ) and not docManager.GetDocuments() and self.IsSDI(
        ):  # Have to open something if it's SDI and there are no projects...
            projectTemplate.CreateDocument(
                '', wx.lib.docview.DOC_NEW).OnNewDocument()

        tips_path = os.path.join(sysutilslib.mainModuleDir, "activegrid",
                                 "tool", "data", "tips.txt")

        # wxBug: On Mac, having the updates fire while the tip dialog is at front
        # for some reason messes up menu updates. This seems a low-level wxWidgets bug,
        # so until I track this down, turn off UI updates while the tip dialog is showing.
        #wx.UpdateUIEvent.SetUpdateInterval(-1)
        #appUpdater = updater.AppUpdateService(self)
        #appUpdater.RunUpdateIfNewer()
        if os.path.isfile(tips_path):
            self.ShowTip(docManager.FindSuitableParent(),
                         wx.CreateFileTipProvider(tips_path, 0))

        wx.UpdateUIEvent.SetUpdateInterval(
            1000
        )  # Overhead of updating menus was too much.  Change to update every n milliseconds.

        # we need this for a while due to the Mac 1.0 release which put things
        # in ~/Documents/ActiveGrid Projects/demos.
        # Now it should be ~/Documents/ActiveGrid Demos/
        base_path = appdirs.documents_folder
        if os.path.isdir(
                os.path.join(base_path, "ActiveGrid Projects", "demos")):
            message = _(
                "The location where demo files are stored has changed between the 1.0 and 1.1 release as a result of improved multi-user support across platforms. In order for ActiveGrid Application Builder to find these files, they need to be moved from '%s/ActiveGrid Projects/demos' to '%s/ActiveGrid Demos'. Click OK to move the files."
            ) % (base_path, base_path)
            wx.MessageBox(message, _("Demo Files Location Update"))
            import shutil
            shutil.copytree(
                os.path.join(base_path, "ActiveGrid Projects", "demos"),
                os.path.join(base_path, "ActiveGrid Demos"))
            shutil.rmtree(os.path.join(base_path, "ActiveGrid Projects"))

        return True
Exemple #30
0
 def __init__(self):
    CResourceEditor.__init__(self)
    ogl.OGLInitialize()
    self.loc["Choice"] = Choice
    self.loc["Dialogue"] = Dialogue