Beispiel #1
0
 def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False):
     self.tabWin = tabWin
     self.viewFrame = Frame(tabWin)
     self.viewFrame.view = self
     self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
     tabWin.add(self.viewFrame, text=tabTitle)
     xmlScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
     self.listBox = Listbox(self.viewFrame, yscrollcommand=xmlScrollbar.set)
     self.listBox.grid(row=0, column=0, sticky=(N, S, E, W))
     #self.listBox.focus_set()
     self.listBox.bind("<Motion>", self.listBoxMotion, '+')
     self.listBox.bind("<1>", self.listBoxClick, '+')
     self.listBox.bind("<Leave>", self.listBoxLeave, '+')
     xmlScrollbar["command"] = self.listBox.yview
     xmlScrollbar.grid(row=0, column=1, sticky=(N, S))
     self.viewFrame.columnconfigure(0, weight=1)
     self.viewFrame.rowconfigure(0, weight=1)
     self.listBoxToolTipText = StringVar()
     if hasToolTip:
         self.listBoxToolTip = ToolTip(self.listBox,
                                       textvariable=self.listBoxToolTipText,
                                       wraplength=480,
                                       follow_mouse=True,
                                       state="disabled")
         self.listBoxRow = -9999999
     self.modelXbrl = modelXbrl
     if modelXbrl:
         modelXbrl.views.append(self)
Beispiel #2
0
    def __init__(self,
                 modelXbrl,
                 tabWin,
                 tabTitle,
                 hasToolTip=False,
                 lang=None):
        self.tabWin = tabWin
        #self.viewFrame = Frame(tabWin)
        #self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        '''
        paneWin = PanedWindow(self.viewFrame, orient=VERTICAL)
        paneWin.grid(row=1, column=0, sticky=(N, S, E, W))
        self.zGrid = scrollgrid(paneWin)
        self.zGrid.grid(row=0, column=0, sticky=(N, S, E, W))
        self.xyGrid = scrollgrid(paneWin)
        self.xyGrid.grid(row=1, column=0, sticky=(N, S, E, W))
        '''
        '''
        self.gridBody = scrollgrid(self.viewFrame)
        self.gridBody.grid(row=0, column=0, sticky=(N, S, E, W))
        '''

        self.viewFrame = scrolledHeaderedFrame(tabWin)
        self.viewFrame.view = self
        self.gridTblHdr = self.viewFrame.tblHdrInterior
        self.gridColHdr = self.viewFrame.colHdrInterior
        self.gridRowHdr = self.viewFrame.rowHdrInterior
        self.gridBody = self.viewFrame.bodyInterior
        '''
        self.viewFrame = scrolledFrame(tabWin)
        self.gridTblHdr = self.gridRowHdr = self.gridColHdr = self.gridBody = self.viewFrame.interior
        '''

        tabWin.add(self.viewFrame, text=tabTitle)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.gridBody.bind("<Motion>", self.motion, '+')
            self.gridBody.bind("<1>", self.onClick, '+')
            self.gridBody.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.gridBody,
                                   textvariable=self.toolTipText,
                                   wraplength=480,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        self.contextMenuClick = self.modelXbrl.modelManager.cntlr.contextMenuClick
        self.gridTblHdr.contextMenuClick = self.contextMenuClick
        self.gridColHdr.contextMenuClick = self.contextMenuClick
        self.gridRowHdr.contextMenuClick = self.contextMenuClick
        self.gridBody.contextMenuClick = self.contextMenuClick
        self.lang = lang
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang:
                self.lang = modelXbrl.modelManager.defaultLang
Beispiel #3
0
 def __init__(self,
              modelXbrl,
              tabWin,
              tabTitle,
              hasToolTip=False,
              lang=None):
     self.tabWin = tabWin
     self.viewFrame = Frame(tabWin)
     self.viewFrame.view = self
     self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
     tabWin.add(self.viewFrame, text=tabTitle)
     self.tabTitle = tabTitle  # for error messages
     vScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
     hScrollbar = Scrollbar(self.viewFrame, orient=HORIZONTAL)
     self.treeView = Treeview(self.viewFrame,
                              xscrollcommand=hScrollbar.set,
                              yscrollcommand=vScrollbar.set)
     self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
     self.treeView.tag_configure("ELR", background="#E0F0FF")
     self.treeView.tag_configure("even", background="#F0F0F0")
     self.treeView.tag_configure("odd", background="#FFFFFF")
     if modelXbrl.modelManager.cntlr.isMac or modelXbrl.modelManager.cntlr.isMSW:
         highlightColor = "#%04x%04x%04x" % self.treeView.winfo_rgb(
             "SystemHighlight")
     else:
         highlightColor = "#33339999ffff"  # using MSW value for Unix/Linux which has no named colors
     self.treeView.tag_configure("selected-ELR", background=highlightColor)
     self.treeView.tag_configure("selected-even", background=highlightColor)
     self.treeView.tag_configure("selected-odd", background=highlightColor)
     self.treeViewSelection = ()
     self.treeView.bind("<<TreeviewSelect>>", self.viewSelectionChange, '+')
     self.treeView.bind("<1>", self.onViewClick, '+')
     hScrollbar["command"] = self.treeView.xview
     hScrollbar.grid(row=1, column=0, sticky=(E, W))
     vScrollbar["command"] = self.treeView.yview
     vScrollbar.grid(row=0, column=1, sticky=(N, S))
     self.viewFrame.columnconfigure(0, weight=1)
     self.viewFrame.rowconfigure(0, weight=1)
     self.modelXbrl = modelXbrl
     self.hasToolTip = hasToolTip
     self.toolTipText = StringVar()
     if hasToolTip:
         self.treeView.bind("<Motion>", self.motion, '+')
         self.treeView.bind("<Leave>", self.leave, '+')
         self.toolTipText = StringVar()
         self.toolTip = ToolTip(self.treeView,
                                textvariable=self.toolTipText,
                                wraplength=480,
                                follow_mouse=True,
                                state="disabled")
         self.toolTipColId = None
         self.toolTipRowId = None
     self.modelXbrl = modelXbrl
     self.lang = lang
     self.labelrole = None
     self.nameIsPrefixed = False
     if modelXbrl:
         modelXbrl.views.append(self)
         if not lang:
             self.lang = modelXbrl.modelManager.defaultLang
Beispiel #4
0
 def __init__(self, parent, url=None, buttonSEC=False, buttonRSS=False):
     super(DialogURL, self).__init__(parent)
     self.parent = parent
     parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
     dialogX = int(parentGeometry.group(3))
     dialogY = int(parentGeometry.group(4))
     self.accepted = False
     self.url = None
     self.transient(self.parent)
     self.title("Enter URL")
     self.urlVar = StringVar()
     self.urlVar.set(url if url is not None else "http://")
     
     frame = Frame(self)
     urlLabel = Label(frame, text=_("URL:"), underline=0)
     urlEntry = Entry(frame, textvariable=self.urlVar, width=60)
     urlEntry.focus_set()
     okButton = Button(frame, text=_("OK"), command=self.ok)
     cancelButton = Button(frame, text=_("Cancel"), command=self.close)
     if buttonSEC:
         usSecButton = Button(frame, text=_("SEC search"), command=self.usSec)
         usSecButton.grid(row=1, column=1, sticky=W, pady=3)
         ToolTip(usSecButton, text=_("Opens US SEC Edgar Company Search (in web browser)\n\n"
                                  "(1) Find the company in web browser,\n"
                                  "(2) Click 'documents' button for desired filing,\n"
                                  "(3) Find 'data files' panel, instance document row, 'document' column,\n"
                                  "(4) On instance document file name, right-click browser menu: 'copy shortcut',\n"
                                  "(5) Come back to this dialog window,\n"
                                  "(6) Ctrl-v (paste) shortcut into above URL text box,\n"
                                  "(7) Click ok button to load instance document"),
                                  wraplength=480)
     if buttonRSS:
         rssButton = Button(frame, text=_("SEC RSS"), command=self.rssFeed)
         rssButton.grid(row=1, column=1, pady=3)
         ToolTip(rssButton, text=_("Opens current US SEC Edgar RSS feed"),
                                  wraplength=480)
     urlLabel.grid(row=0, column=0, sticky=W, pady=3, padx=3)
     urlEntry.grid(row=0, column=1, columnspan=3, sticky=EW, pady=3, padx=3)
     okButton.grid(row=1, column=2, sticky=E, pady=3)
     ToolTip(okButton, text=_("Opens above URL from web cache, downloading to cache if necessary"), wraplength=240)
     cancelButton.grid(row=1, column=3, sticky=EW, pady=3, padx=3)
     ToolTip(cancelButton, text=_("Cancel operation"))
                 
     frame.grid(row=0, column=0, sticky=(N,S,E,W))
     frame.columnconfigure(1, weight=1)
     window = self.winfo_toplevel()
     window.columnconfigure(0, weight=1)
     self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
     
     self.bind("<Alt-u>", lambda *ignore: urlEntry.focus_set())
     self.bind("<Return>", self.ok)
     self.bind("<Escape>", self.close)
     
     self.protocol("WM_DELETE_WINDOW", self.close)
     self.grab_set()
     self.wait_window(self)
Beispiel #5
0
    def __init__(self, mainWin, options):
        self.mainWin = mainWin
        parent = mainWin.parent
        super(DialogNewFactItemOptions, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("New Fact Item Options"))
        
        frame = Frame(self)

        label(frame, 1, 1, "Entity scheme:")
        self.cellEntityIdentScheme = gridCell(frame, 2, 1, getattr(options,"entityIdentScheme",""), width=50)
        ToolTip(self.cellEntityIdentScheme, text=_("Enter the scheme for the context entity identifier"), wraplength=240)
        label(frame, 1, 2, "Entity identifier:")
        self.cellEntityIdentValue = gridCell(frame, 2, 2, getattr(options,"entityIdentValue",""))
        ToolTip(self.cellEntityIdentValue, text=_("Enter the entity identifier value (e.g., stock ticker)"), wraplength=240)
        label(frame, 1, 3, "Start date:")
        startDate = getattr(options,"startDate",None)
        self.cellStartDate = gridCell(frame, 2, 3, XmlUtil.dateunionValue(startDate) if startDate else "")
        ToolTip(self.cellStartDate, text=_("Enter the start date for the report period (e.g., 2010-01-01)"), wraplength=240)
        label(frame, 1, 4, "End date:")
        endDate = getattr(options,"endDate",None)
        self.cellEndDate = gridCell(frame, 2, 4, XmlUtil.dateunionValue(endDate, subtractOneDay=True) if endDate else "")
        ToolTip(self.cellEndDate, text=_("Enter the end date for the report period (e.g., 2010-12-31)"), wraplength=240)
        label(frame, 1, 5, "Monetary unit:")
        self.cellMonetaryUnit = gridCombobox(frame, 2, 5, getattr(options,"monetaryUnit",""), values=monetaryUnits)
        ToolTip(self.cellMonetaryUnit, text=_("Select a monetary unit (e.g., EUR)"), wraplength=240)
        label(frame, 1, 6, "Monetary decimals:")
        self.cellMonetaryDecimals = gridCell(frame, 2, 6, getattr(options,"monetaryDecimals","2"))
        ToolTip(self.cellMonetaryDecimals, text=_("Enter decimals for monetary items"), wraplength=240)
        label(frame, 1, 7, "Non-monetary decimals:")
        self.cellNonMonetaryDecimals = gridCell(frame, 2, 7, getattr(options,"nonMonetaryDecimals","0"))
        ToolTip(self.cellNonMonetaryDecimals, text=_("Enter decimals for non-monetary items (e.g., stock shares)"), wraplength=240)

        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=8, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #6
0
def sphinxDialogRssWatchFileChoices(dialog, frame, row, options, cntlr, openFileImage, openDatabaseImage):
    from tkinter import PhotoImage, N, S, E, W
    try:
        from tkinter.ttk import Button
    except ImportError:
        from ttk import Button
    from arelle.CntlrWinTooltip import ToolTip
    from arelle.UiUtil import gridCell, label
    # add sphinx formulas to RSS dialog
    def chooseSphinxFiles():
        sphinxFilesList = cntlr.uiFileDialog("open",
                multiple=True,  # expect multiple sphinx files
                title=_("arelle - Select sphinx rules file"),
                initialdir=cntlr.config.setdefault("rssWatchSphinxRulesFilesDir","."),
                filetypes=[(_("Sphinx files .xsr"), "*.xsr"), (_("Sphinx archives .xrb"), "*.xrb")],
                defaultextension=".xsr")
        if sphinxFilesList:
            dialog.options["rssWatchSphinxRulesFilesDir"] = os.path.dirname(sphinxFilesList[0])
            sphinxFilesPipeSeparated = '|'.join(sphinxFilesList)
            dialog.options["sphinxRulesFiles"] = sphinxFilesPipeSeparated
            dialog.cellSphinxFiles.setValue(sphinxFilesPipeSeparated)
        else:  # deleted
            dialog.options.pop("sphinxRulesFiles", "")  # remove entry
    label(frame, 1, row, "Sphinx rules:")
    dialog.cellSphinxFiles = gridCell(frame,2, row, options.get("sphinxRulesFiles",""))
    ToolTip(dialog.cellSphinxFiles, text=_("Select a sphinx rules (file(s) or archive(s)) to to evaluate each filing.  "
                                           "The results are recorded in the log file.  "), wraplength=240)
    chooseFormulaFileButton = Button(frame, image=openFileImage, width=12, command=chooseSphinxFiles)
    chooseFormulaFileButton.grid(row=row, column=3, sticky=W)
Beispiel #7
0
    def __init__(self,
                 modelXbrl,
                 tabWin,
                 tabTitle,
                 contentView,
                 hasToolTip=False,
                 lang=None):
        self.tabWin = tabWin

        self.viewFrame = contentView
        self.viewFrame.view = self

        tabWin.add(self.viewFrame, text=tabTitle)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.gridBody,
                                   textvariable=self.toolTipText,
                                   wraplength=480,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        modelManager = self.modelXbrl.modelManager
        self.contextMenuClick = modelManager.cntlr.contextMenuClick
        self.lang = lang
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang:
                self.lang = modelXbrl.modelManager.defaultLang
Beispiel #8
0
 def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False, lang=None):
     self.tabWin = tabWin
     #self.viewFrame = Frame(tabWin)
     #self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
     '''
     paneWin = PanedWindow(self.viewFrame, orient=VERTICAL)
     paneWin.grid(row=1, column=0, sticky=(N, S, E, W))
     self.zGrid = scrollgrid(paneWin)
     self.zGrid.grid(row=0, column=0, sticky=(N, S, E, W))
     self.xyGrid = scrollgrid(paneWin)
     self.xyGrid.grid(row=1, column=0, sticky=(N, S, E, W))
     '''
     '''
     self.gridBody = scrollgrid(self.viewFrame)
     self.gridBody.grid(row=0, column=0, sticky=(N, S, E, W))
     '''
     
     self.viewFrame = scrolledHeaderedFrame(tabWin)
     self.viewFrame.view = self
     self.gridTblHdr = self.viewFrame.tblHdrInterior
     self.gridColHdr = self.viewFrame.colHdrInterior
     self.gridRowHdr = self.viewFrame.rowHdrInterior
     self.gridBody = self.viewFrame.bodyInterior
     '''
     self.viewFrame = scrolledFrame(tabWin)
     self.gridTblHdr = self.gridRowHdr = self.gridColHdr = self.gridBody = self.viewFrame.interior
     '''
     
     tabWin.add(self.viewFrame,text=tabTitle)
     self.modelXbrl = modelXbrl
     self.hasToolTip = hasToolTip
     self.toolTipText = StringVar()
     if hasToolTip:
         self.gridBody.bind("<Motion>", self.motion, '+')
         self.gridBody.bind("<1>", self.onClick, '+')
         self.gridBody.bind("<Leave>", self.leave, '+')
         self.toolTipText = StringVar()
         self.toolTip = ToolTip(self.gridBody, 
                                textvariable=self.toolTipText, 
                                wraplength=480, 
                                follow_mouse=True,
                                state="disabled")
         self.toolTipColId = None
         self.toolTipRowId = None
     self.modelXbrl = modelXbrl
     self.contextMenuClick = self.modelXbrl.modelManager.cntlr.contextMenuClick
     self.gridTblHdr.contextMenuClick = self.contextMenuClick
     self.gridColHdr.contextMenuClick = self.contextMenuClick
     self.gridRowHdr.contextMenuClick = self.contextMenuClick
     self.gridBody.contextMenuClick = self.contextMenuClick
     self.lang = lang
     if modelXbrl:
         modelXbrl.views.append(self)
         if not lang: 
             self.lang = modelXbrl.modelManager.defaultLang
Beispiel #9
0
 def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False, lang=None):
     self.tabWin = tabWin
     self.viewFrame = Frame(tabWin)
     self.viewFrame.view = self
     self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
     tabWin.add(self.viewFrame,text=tabTitle)
     self.tabTitle = tabTitle # for error messages
     vScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
     hScrollbar = Scrollbar(self.viewFrame, orient=HORIZONTAL)
     self.treeView = Treeview(self.viewFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
     self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
     self.treeView.tag_configure("ELR", background="#E0F0FF")
     self.treeView.tag_configure("even", background="#F0F0F0")
     self.treeView.tag_configure("odd", background="#FFFFFF")
     if modelXbrl.modelManager.cntlr.isMac or modelXbrl.modelManager.cntlr.isMSW:
         highlightColor = "#%04x%04x%04x" % self.treeView.winfo_rgb("SystemHighlight")
     else:
         highlightColor = "#33339999ffff"  # using MSW value for Unix/Linux which has no named colors
     self.treeView.tag_configure("selected-ELR", background=highlightColor)
     self.treeView.tag_configure("selected-even", background=highlightColor)
     self.treeView.tag_configure("selected-odd", background=highlightColor)
     self.treeViewSelection = ()
     self.treeView.bind("<<TreeviewSelect>>", self.viewSelectionChange, '+')
     self.treeView.bind("<1>", self.onViewClick, '+')
     hScrollbar["command"] = self.treeView.xview
     hScrollbar.grid(row=1, column=0, sticky=(E,W))
     vScrollbar["command"] = self.treeView.yview
     vScrollbar.grid(row=0, column=1, sticky=(N,S))
     self.viewFrame.columnconfigure(0, weight=1)
     self.viewFrame.rowconfigure(0, weight=1)
     self.modelXbrl = modelXbrl
     self.hasToolTip = hasToolTip
     self.toolTipText = StringVar()
     if hasToolTip:
         self.treeView.bind("<Motion>", self.motion, '+')
         self.treeView.bind("<Leave>", self.leave, '+')
         self.toolTipText = StringVar()
         self.toolTip = ToolTip(self.treeView, 
                                textvariable=self.toolTipText, 
                                wraplength=480, 
                                follow_mouse=True,
                                state="disabled")
         self.toolTipColId = None
         self.toolTipRowId = None
     self.modelXbrl = modelXbrl
     self.lang = lang
     self.labelrole = None
     self.nameIsPrefixed = False
     if modelXbrl:
         modelXbrl.views.append(self)
         if not lang: 
             self.lang = modelXbrl.modelManager.defaultLang
Beispiel #10
0
 def initFilledFirstCellOpenRow(self, label, x, y, objectId=None, command=None):
     #TODO: change this ugly button + label cell content and add a dedicated table column
     #      for the delete button (with some prettier face)
     #      and at least make those borders look better.
     cellIndex = '%i,%i'% (y, x)
     frame = Frame(self)
     frame.columnconfigure(0, weight=0)
     frame.columnconfigure(1, weight=1)
     
     b = Button(frame, text="X", command=command, width=2)
     ToolTip(b, text=_("Delete Line"))
     b.grid(row=0, column=0, sticky=(N, E, S, W), padx=0, pady=0)
     
     lbl = Label(frame, text=label, background='#d00d00d00', anchor=E)
     lbl.grid(row=0, column=1, sticky=(N, E, S, W), padx=0, pady=0)
     self.window_configure(cellIndex, window=frame, sticky=(N, E, S, W))            
Beispiel #11
0
 def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False):
     self.tabWin = tabWin
     self.viewFrame = Frame(tabWin)
     self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
     tabWin.add(self.viewFrame,text=tabTitle)
     xmlScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
     self.listBox = Listbox(self.viewFrame, yscrollcommand=xmlScrollbar.set)
     self.listBox.grid(row=0, column=0, sticky=(N, S, E, W))
     #self.listBox.focus_set()
     self.listBox.bind("<Motion>", self.listBoxMotion, '+')
     self.listBox.bind("<Leave>", self.listBoxLeave, '+')
     xmlScrollbar["command"] = self.listBox.yview
     xmlScrollbar.grid(row=0, column=1, sticky=(N,S))
     self.viewFrame.columnconfigure(0, weight=1)
     self.viewFrame.rowconfigure(0, weight=1)
     self.listBoxToolTipText = StringVar()
     if hasToolTip:
         self.listBoxToolTip = ToolTip(self.listBox, textvariable=self.listBoxToolTipText, wraplength=480, follow_mouse=True, state="disabled")
         self.listBoxRow = -9999999
     self.modelXbrl = modelXbrl
     if modelXbrl:
         modelXbrl.views.append(self)
Beispiel #12
0
def xbrlDBdialogRssWatchDBconnection(dialog, frame, row, options, cntlr,
                                     openFileImage, openDatabaseImage):
    from tkinter import PhotoImage, N, S, E, W
    try:
        from tkinter.ttk import Button
        from tkinter.simpledialog import askstring
    except ImportError:
        from ttk import Button
    from arelle.CntlrWinTooltip import ToolTip
    from arelle.UiUtil import gridCell, label

    # add sphinx formulas to RSS dialog
    def enterConnectionString():
        from arelle.DialogUserPassword import askDatabase
        # (user, password, host, port, database)
        db = askDatabase(
            cntlr.parent,
            dialog.cellDBconnection.value.split(',')
            if dialog.cellDBconnection.value else None)
        if db:
            dbConnectionString = ','.join(db)
            dialog.options["xbrlDBconnection"] = dbConnectionString
            dialog.cellDBconnection.setValue(dbConnectionString)
        else:  # deleted
            dialog.options.pop("xbrlDBconnection", "")  # remove entry

    label(frame, 1, row, "DB Connection:")
    dialog.cellDBconnection = gridCell(frame, 2, row,
                                       options.get("xbrlDBconnection", ""))
    ToolTip(dialog.cellDBconnection,
            text=_("Enter an XBRL Database (Postgres) connection string.  "
                   "E.g., pg://dbuser:dbpassword@dbhost:port.  "),
            wraplength=240)
    enterDBconnectionButton = Button(frame,
                                     image=openDatabaseImage,
                                     width=12,
                                     command=enterConnectionString)
    enterDBconnectionButton.grid(row=row, column=3, sticky=W)
Beispiel #13
0
    def __init__(self, mainWin, modelXbrl):
        parent = mainWin.parent
        super(DialogArcroleGroup, self).__init__(parent)
        self.mainWin = mainWin
        self.parent = parent
        self.modelXbrl = modelXbrl
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.selectedGroup = None

        self.transient(self.parent)
        self.title(_("Select Arcrole Group"))

        frame = Frame(self)
        '''
        dialogFrame = Frame(frame, width=500)
        dialogFrame.columnconfigure(0, weight=1)
        dialogFrame.rowconfigure(0, weight=1)
        dialogFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        '''

        # mainWin.showStatus(_("loading formula options and parameters"))

        # load grid
        groupLabel = label(frame, 1, 0, _("Group:"))
        self.arcroleGroups = mainWin.config.get("arcroleGroups", {})
        arcroleGroupSelected = self.mainWin.config.get("arcroleGroupSelected")
        if arcroleGroupSelected in self.arcroleGroups:
            arcroleGroup = self.arcroleGroups[arcroleGroupSelected]
        else:
            arcroleGroup = []
            arcroleGroupSelected = None
        self.groupName = gridCombobox(frame,
                                      2,
                                      0,
                                      value=arcroleGroupSelected,
                                      values=sorted(self.arcroleGroups.keys()),
                                      comboboxselected=self.comboBoxSelected)
        groupToolTipMessage = _(
            "Select an existing arcrole group, or enter a name for a new arcrole group.  "
            "If selecting an existing group, it can be edited, and changes will be saved in the config file.  "
            "If nothing is changed for an existing group, the saved setting is not disturbed.  "
            "Arcroles with checkboxes below are shown only for arcroles that have relationships in the loaded DTS, "
            "but if an existing group is selected with more arcroles (that were not in the current DTS) then "
            "the prior setting with not-present arcroles is preserved. ")
        ToolTip(self.groupName, text=groupToolTipMessage, wraplength=360)
        ToolTip(groupLabel, text=groupToolTipMessage, wraplength=360)
        clearImage = PhotoImage(
            file=os.path.join(mainWin.imagesDir, "toolbarDelete.gif"))
        clearGroupNameButton = Button(frame,
                                      image=clearImage,
                                      width=12,
                                      command=self.clearGroupName)
        clearGroupNameButton.grid(row=0, column=3, sticky=W)
        ToolTip(
            clearGroupNameButton,
            text=
            _("Remove the currently selected arcrole group from the config file. "
              "After removing, you may select another arcrole, but must select 'OK' for the "
              "removal to be saved. "),
            wraplength=240)
        arcrolesLabel = label(frame, 1, 1, _("Arcroles:"))
        ToolTip(
            arcrolesLabel,
            text=_("Shows all the arcroles that are present in this DTS. "),
            wraplength=240)
        from arelle.ModelRelationshipSet import baseSetArcroles
        self.options = {}
        self.checkboxes = []
        y = 1
        for name, arcrole in baseSetArcroles(self.modelXbrl):
            if arcrole.startswith("http://"):
                self.options[arcrole] = arcrole in arcroleGroup
                self.checkboxes.append(
                    checkbox(frame, 2, y, name[1:], arcrole, columnspan=2))
                y += 1

        mainWin.showStatus(None)

        self.options[
            XbrlConst.
            arcroleGroupDetect] = XbrlConst.arcroleGroupDetect in arcroleGroup
        self.autoOpen = checkbox(frame, 1, y, _("detect"),
                                 XbrlConst.arcroleGroupDetect)
        self.autoOpen.grid(sticky=W, columnspan=2)
        self.checkboxes.append(self.autoOpen)
        ToolTip(
            self.autoOpen,
            text=
            _("If checked, this arcrole group will be detected if any arcrole of the group is present in a DTS, for example to open a treeview pane. "
              ),
            wraplength=240)
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        cancelButton = Button(frame,
                              text=_("Cancel"),
                              width=8,
                              command=self.close)
        cancelButton.grid(row=y,
                          column=1,
                          sticky=E,
                          columnspan=3,
                          pady=3,
                          padx=3)
        okButton.grid(row=y, column=1, sticky=E, columnspan=3, pady=3, padx=64)
        ToolTip(
            okButton,
            text=
            _("Open a treeview with named arcrole group and selected arcroles. "
              "If any changes were made to checkboxes or name, save in the config. "
              ),
            wraplength=240)
        ToolTip(
            cancelButton,
            text=
            _("Close this dialog, without saving arcrole group changes or opening a view pane. "
              ),
            wraplength=240)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(1, weight=3)
        frame.columnconfigure(2, weight=1)
        frame.columnconfigure(3, weight=3)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #14
0
class DialogOpenArchive(Toplevel):
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(mainWin, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                # may be a catalog file with no entry oint names
                if not self.taxonomyPackage["nameToUrls"]:
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return
    
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
        
    def loadTreeView(self, openType, title, colHeader):
        self.title(title)
        self.openType = openType
        selectedNode = None

        # clear previous treeview entries
        for previousNode in self.treeView.get_children(""): 
            self.treeView.delete(previousNode)

        # set up treeView widget and tabbed pane
        if openType in (ARCHIVE, DISCLOSURE_SYSTEM):
            self.treeView.column("#0", width=500, anchor="w")
            self.treeView.heading("#0", text=colHeader)
            try:
                self.isRss = self.filesource.isRss
                if self.isRss:
                    self.treeView.column("#0", width=350, anchor="w")
                    self.treeView["columns"] = ("descr", "date", "instDoc")
                    self.treeView.column("descr", width=50, anchor="center", stretch=False)
                    self.treeView.heading("descr", text="Form")
                    self.treeView.column("date", width=170, anchor="w", stretch=False)
                    self.treeView.heading("date", text="Pub Date")
                    self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
                    self.treeView.heading("instDoc", text="Instance Document")
            except AttributeError:
                self.isRss = False
                self.treeView["columns"] = tuple()
        
            loadedPaths = []
            for i, filename in enumerate(self.filenames):
                if isinstance(filename,tuple):
                    if self.isRss:
                        form, date, instDoc = filename[2:5]
                    filename = filename[0] # ignore tooltip
                    self.hasToolTip = True
                if filename.endswith("/"):
                    filename = filename[:-1]
                path = filename.split("/")
                if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                    parent = "file{0}".format(loadedPaths.index(path[:-1]))
                else:
                    parent = "" 
                node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc", os.path.basename(instDoc))
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=150, anchor="w")
            self.treeView.heading("#0", text="Name")
    
            self.treeView["columns"] = ("url",)
            self.treeView.column("url", width=350, anchor="w")
            self.treeView.heading("url", text="URL")
            
            for name, urls in self.taxonomyPackage["nameToUrls"].items():
                displayUrl = urls[1] # display the canonical URL
                self.treeView.insert("", "end", name, values=[displayUrl], text=name)
                
            self.hasToolTip = True
        else: # unknown openType
            return None
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)

        if self.showAltViewButton:
            self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries"))

        
    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            if hasattr(self, "taxonomyPackage"):
                # load file source remappings
                self.filesource.mappedPaths = self.taxonomyPackage["remappings"]
            filename = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                filename = self.filenames[int(selection[0][4:])]
                if isinstance(filename,tuple):
                    if self.isRss:
                        filename = filename[4]
                    else:
                        filename = filename[0]
            elif self.openType == ENTRY_POINTS:
                epName = selection[0]
                #index 0 is the remapped Url, as opposed to the canonical one used for display
                filename = self.taxonomyPackage["nameToUrls"][epName][0]
                if not filename.endswith("/"):
                    # check if it's an absolute URL rather than a path into the archive
                    if not isHttpUrl(filename) and self.metadataFilePrefix != self.taxonomyPkgMetaInf:
                        # assume it's a path inside the archive:
                        filename = self.metadataFilePrefix + filename
            if filename is not None and not filename.endswith("/"):
                if hasattr(self, "taxonomyPackage"):
                    # attempt to unmap the filename to original file
                    # will be mapped again in loading, but this allows schemaLocation to be unmapped
                    for prefix, remapping in self.taxonomyPackage["remappings"].items():
                        if isHttpUrl(remapping):
                            remapStart = remapping
                        else:
                            remapStart = self.metadataFilePrefix + remapping
                        if filename.startswith(remapStart):
                            # set unmmapped file
                            filename = prefix + filename[len(remapStart):]
                            break
                self.filesource.select(filename)
                self.accepted = True
                self.close()
                        
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
        
    def showAltView(self, event=None):
        if self.openType == ENTRY_POINTS:
            self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File"))
        else:
            self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File"))
        
    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvRowId != self.toolTipRowId:
            text = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                self.toolTipRowId = tvRowId
                if tvRowId and len(tvRowId) > 4:
                    try:
                        text = self.filenames[ int(tvRowId[4:]) ]
                        if isinstance(text, tuple):
                            text = text[1].replace("\\n","\n")
                    except (KeyError, ValueError):
                        pass
            elif self.openType == ENTRY_POINTS:
                try:
                    epUrl = self.taxonomyPackage["nameToUrls"][tvRowId][1]
                    text = "{0}\n{1}".format(tvRowId, epUrl)
                except KeyError:
                    pass
            self.setToolTip(text)
                
    def setToolTip(self, text):
        self.toolTip._hide()
        if text:
            self.toolTipText.set(text)
            self.toolTip.configure(state="normal")
            self.toolTip._schedule()
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")
Beispiel #15
0
    def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent # parent is cntlrWinMain
        else: # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(cntlr, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                
                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html"):
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(".xhtml"):
                                _type = "Inline Instance"
                                self.packageContainedInstances.append([potentialInstance, _type])
                                packageContentTypeCounts[potentialInstance] = packageContentTypeCounts.get(potentialInstance, 0) + 1
                        if self.packageContainedInstances:
                            break 
                    if self.packageContainedInstances: # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][0] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][0] = "{} {}".format(_type, _dupNo)
                                    
                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return
    
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)
        
        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        
        self.wait_window(self)
Beispiel #16
0
class ViewTree:
    def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False, lang=None, editableColumns=[], valueChangedCallback=None):
        self.tabWin = tabWin
        self.viewFrame = Frame(tabWin)
        self.viewFrame.view = self
        self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        tabWin.add(self.viewFrame,text=tabTitle)
        self.tabTitle = tabTitle # for error messages
        vScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(self.viewFrame, orient=HORIZONTAL)
        self.isEbaTableIndex = False
        if tabTitle.startswith('Tables'):
            for pluginXbrlMethod in pluginClassMethods("CntlrWinMain.Modeling.LoadFilingIndicators"):
                self.isEbaTableIndex = True
                # for EBA and in case of table index, add a second column with the filing indicator
                # (OK, it is not really sound to base this test on the title)            
                self.treeView = Treeview(self.viewFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, columns="Filing")
                break
        if not self.isEbaTableIndex:
            self.treeView = Treeview(self.viewFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.treeView.tag_configure("ELR", background="#E0F0FF")
        self.treeView.tag_configure("even", background="#F0F0F0")
        self.treeView.tag_configure("odd", background="#FFFFFF")
        if modelXbrl.modelManager.cntlr.isMac or modelXbrl.modelManager.cntlr.isMSW:
            highlightColor = "#%04x%04x%04x" % self.treeView.winfo_rgb("SystemHighlight")
        else:
            highlightColor = "#33339999ffff"  # using MSW value for Unix/Linux which has no named colors
        self.treeView.tag_configure("selected-ELR", background=highlightColor)
        self.treeView.tag_configure("selected-even", background=highlightColor)
        self.treeView.tag_configure("selected-odd", background=highlightColor)
        self.treeViewSelection = ()
        self.treeView.bind("<<TreeviewSelect>>", self.viewSelectionChange, '+')
        self.treeView.bind("<1>", self.onViewClick, '+')
        self.treeView.bind("<Double-1>", self.onDoubleClick, '+')
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        self.viewFrame.columnconfigure(0, weight=1)
        self.viewFrame.rowconfigure(0, weight=1)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=480, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        self.lang = lang
        self.labelrole = None
        self.nameIsPrefixed = False
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang: 
                self.lang = modelXbrl.modelManager.defaultLang
        self.editableColumns = editableColumns
        self.valueChangedCallback = valueChangedCallback
        self.entryPopup = None

    def refreshTitle(self):
        tid = str(self.viewFrame)
        text = "Tables (" + self.modelXbrl.getInstanceFilenameForView() + ")"
        self.tabWin.tab(tid, text=text)
        self.tabTitle = text
            
    def clearTreeView(self):
        self.treeViewSelection = ()
        for node in self.treeView.get_children():
            self.treeView.delete(node)
                
    def viewSelectionChange(self, event=None):
        for node in self.treeViewSelection:
            self.removeSelection(node)
        self.treeViewSelection = self.treeView.selection()
        for node in self.treeViewSelection:
            self.addSelection(node)
            
    def removeSelection(self, node):
        if self.treeView.exists(node):
            priorTags = self.treeView.item(node)["tags"]
            if priorTags:
                newTags = tuple((i[9:] if i.startswith("selected-") else i) for i in priorTags)
                self.treeView.item(node, tags=newTags)


    def addSelection(self, node):
        priorTags = self.treeView.item(node)["tags"]
        if priorTags:
            newTags = tuple(("selected-"+i if i in ['even', 'odd'] else i) for i in priorTags)
            self.treeView.item(node, tags=newTags)

    def onViewClick(self, *args):
        self.modelXbrl.modelManager.cntlr.currentView = self

    def close(self):
        del self.viewFrame.view
        if self.modelXbrl:
            self.tabWin.forget(self.viewFrame)
            self.modelXbrl.views.remove(self)
            self.modelXbrl = None
            self.view = None
                
    def select(self):
        self.tabWin.select(self.viewFrame)
        
    def leave(self, *args):
        self.toolTipColId = None
        self.toolTipRowId = None

    def motion(self, *args):
        tvColId = self.treeView.identify_column(args[0].x)
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvColId != self.toolTipColId or tvRowId != self.toolTipRowId:
            self.toolTipColId = tvColId
            self.toolTipRowId = tvRowId
            newValue = self.getToolTip(tvRowId, tvColId)
            if newValue is None and tvRowId and len(tvRowId) > 0:
                try:
                    col = int(tvColId[1:])
                    if col == 0:
                        newValue = self.treeView.item(tvRowId,"text")
                    else:
                        values = self.treeView.item(tvRowId,"values")
                        if col <= len(values):
                            newValue = values[col - 1]
                except ValueError:
                    pass
            self.setToolTip(newValue, tvColId)
            
    def getToolTip(self, rowId, colId):
        return None
                
    def setToolTip(self, text, colId="#0"):
        self.toolTip._hide()
        if isinstance(text,str) and len(text) > 0:
            width = self.treeView.column(colId,"width")
            if len(text) * 8 > width or '\n' in text:
                self.toolTipText.set(text)
                self.toolTip.configure(state="normal")
                self.toolTip._schedule()
            else:
                self.toolTipText.set("")
                self.toolTip.configure(state="disabled")
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")

    def contextMenu(self):
        try:
            return self.menu
        except AttributeError:
            try:
                self.menu = Menu( self.viewFrame, tearoff = 0 )
                self.treeView.bind( self.modelXbrl.modelManager.cntlr.contextMenuClick, self.popUpMenu, '+' )
                return self.menu
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating context menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None
                return None

    def popUpMenu(self, event):
        if self.menu:
            self.menuRow = self.treeView.identify_row(event.y)
            self.menuCol = self.treeView.identify_column(event.x)
            self.menu.post( event.x_root, event.y_root )
        
    def expand(self):
        self.setTreeItemOpen(self.menuRow,open=True)
        
    def setFiling(self, filingIndicator):
        # Check if there is a custom method to set filing indicators
        for pluginXbrlMethod in pluginClassMethods("CntlrWinMain.Rendering.SetFilingIndicator"):
            stopPlugin = pluginXbrlMethod(self, self.modelXbrl, filingIndicator)
            if stopPlugin:
                break;
        
    def setFilingTrue(self):
        self.setFiling(True)
        
    def setFilingFalse(self):
        self.setFiling(False)
        
    def resetFiling(self):
        self.setFiling(None)

    def expandAll(self):
        self.setTreeItemOpen("",open=True)
        
    def collapse(self):
        self.setTreeItemOpen(self.menuRow,open=False)
        
    def collapseAll(self):
        self.setTreeItemOpen("",open=False)
        
    def setTreeItemOpen(self, node, open=True):
        if node:
            self.treeView.item(node, open=open)
        for childNode in self.treeView.get_children(node):
            self.setTreeItemOpen(childNode, open)
            
    def menuAddExpandCollapse(self):
        if self.menu:
            self.menu.add_command(label=_("Expand"), underline=0, command=self.expand)
            self.menu.add_command(label=_("Collapse"), underline=0, command=self.collapse)
            self.menu.add_command(label=_("Expand all"), underline=0, command=self.expandAll)
            self.menu.add_command(label=_("Collapse all"), underline=0, command=self.collapseAll)
            
    def menuAddFilingChoice(self):
        if self.menu:
            self.menu.add_command(label=_("Filing: set filed"), underline=0, command=self.setFilingTrue)
            self.menu.add_command(label=_("Filing: set not filed"), underline=0, command=self.setFilingFalse)
            self.menu.add_command(label=_("Filing: clear"), underline=0, command=self.resetFiling)
        
    def menuAddClipboard(self):
        if self.menu and self.modelXbrl.modelManager.cntlr.hasClipboard:
            try:
                clipboardMenu = Menu(self.viewFrame, tearoff=0)
                clipboardMenu.add_command(label=_("Cell"), underline=0, command=self.copyCellToClipboard)
                clipboardMenu.add_command(label=_("Row"), underline=0, command=self.copyRowToClipboard)
                clipboardMenu.add_command(label=_("Table"), underline=0, command=self.copyTableToClipboard)
                self.menu.add_cascade(label=_("Copy to clipboard"), menu=clipboardMenu, underline=0)
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating clipboard menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None
        
    def menuAddLangs(self):
        if self.menu:
            try:
                langsMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=_("Language"), menu=langsMenu, underline=0)
                for lang in sorted(self.modelXbrl.langs):
                    langsMenu.add_command(label=lang, underline=0, command=lambda l=lang: self.setLang(l))
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating context languages menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None

    def menuAddLabelRoles(self, includeConceptName=False, menulabel=None):
        if self.menu:
            try:
                if menulabel is None: menulabel = _("Label role")
                rolesMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=menulabel, menu=rolesMenu, underline=0)
                from arelle.ModelRelationshipSet import labelroles
                for x in labelroles(self.modelXbrl, includeConceptName):
                    rolesMenu.add_command(label=x[0][1:], underline=0, command=lambda a=x[1]: self.setLabelrole(a))
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating context label roles menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None

    def menuAddNameStyle(self, menulabel=None):
        if self.menu:
            try:
                if menulabel is None: menulabel = _("Name Style")
                nameStyleMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=menulabel, menu=nameStyleMenu, underline=0)
                from arelle.ModelRelationshipSet import labelroles
                nameStyleMenu.add_command(label=_("Prefixed"), underline=0, command=lambda a=True: self.setNamestyle(a))
                nameStyleMenu.add_command(label=_("No prefix"), underline=0, command=lambda a=False: self.setNamestyle(a))
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating context name style menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None

    def menuAddUnitDisplay(self):
        if self.menu:
            try:
                rolesMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=_("Units"), menu=rolesMenu, underline=0)
                rolesMenu.add_command(label=_("Unit ID"), underline=0, command=lambda: self.setUnitDisplay(unitDisplayID=True))
                rolesMenu.add_command(label=_("Measures"), underline=0, command=lambda: self.setUnitDisplay(unitDisplayID=False))
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating context unit menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None

    def menuAddViews(self, addClose=True, tabWin=None):
        if self.menu:
            try:
                if tabWin is None: tabWin = self.tabWin
                viewMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=_("View"), menu=viewMenu, underline=0)
                newViewsMenu = Menu(self.viewFrame, tearoff=0)
                if addClose:
                    viewMenu.add_command(label=_("Close"), underline=0, command=self.close)
                viewMenu.add_cascade(label=_("Additional view"), menu=newViewsMenu, underline=0)
                newViewsMenu.add_command(label=_("Arcrole group..."), underline=0, command=lambda: self.newArcroleGroupView(tabWin))
                from arelle.ModelRelationshipSet import baseSetArcroles
                for x in baseSetArcroles(self.modelXbrl) + [( " Role Types","!CustomRoleTypes!"), (" Arcrole Types", "!CustomArcroleTypes!")]:
                    newViewsMenu.add_command(label=x[0][1:], underline=0, command=lambda a=x[1]: self.newView(a, tabWin))
            except Exception as ex: # tkinter menu problem maybe
                self.modelXbrl.info("arelle:internalException",
                                    _("Exception creating context add-views menu in %(title)s: %(error)s"),
                                    modelObject=self.modelXbrl.modelDocument, title=self.tabTitle, error=str(ex))
                self.menu = None
    
    def newView(self, arcrole, tabWin):
        if arcrole in ("!CustomRoleTypes!", "!CustomArcroleTypes!"):
            from arelle import ViewWinRoleTypes
            ViewWinRoleTypes.viewRoleTypes(self.modelXbrl, tabWin, arcrole=="!CustomArcroleTypes!", lang=self.lang)
        else:
            from arelle import ViewWinRelationshipSet
            ViewWinRelationshipSet.viewRelationshipSet(self.modelXbrl, tabWin, arcrole, lang=self.lang)
            
    def newArcroleGroupView(self, tabWin):
        from arelle.DialogArcroleGroup import getArcroleGroup
        from arelle import ViewWinRelationshipSet
        arcroleGroup = getArcroleGroup(self.modelXbrl.modelManager.cntlr, self.modelXbrl)
        if arcroleGroup: 
            ViewWinRelationshipSet.viewRelationshipSet(self.modelXbrl, tabWin, arcroleGroup, lang=self.lang)
            
    def setLang(self, lang):
        self.lang = lang
        self.view()
        
    def setLabelrole(self, labelrole):
        self.labelrole = labelrole
        self.view()
        
    def setNamestyle(self, isPrefixed):
        self.nameIsPrefixed = isPrefixed
        self.view()
        
    def setUnitDisplay(self, unitDisplayID=False):
        self.unitDisplayID = unitDisplayID
        self.view()
        
    def setColumnsSortable(self, treeColIsInt=False, startUnsorted=False, initialSortCol="#0", initialSortDirForward=True):
        if hasattr(self, 'lastSortColumn') and self.lastSortColumn:
            self.treeView.heading(self.lastSortColumn, image=self.sortImages[2])
        self.lastSortColumn = None if startUnsorted else initialSortCol 
        self.lastSortColumnForward = initialSortDirForward
        self.treeColIsInt = treeColIsInt
        if not hasattr(self, "sortImages"):
            self.sortImages = (PhotoImage(file=os.path.join(self.modelXbrl.modelManager.cntlr.imagesDir, "columnSortUp.gif")),
                               PhotoImage(file=os.path.join(self.modelXbrl.modelManager.cntlr.imagesDir, "columnSortDown.gif")),
                               PhotoImage())
        for col in ("#0",) + self.treeView["columns"]:
            self.treeView.heading(col, command=lambda c=col: self.sortColumn(c))
        if not startUnsorted:
            self.treeView.heading(initialSortCol, image=self.sortImages[not initialSortDirForward])
            
    def colSortVal(self, node, col):
        if col == "#0":
            treeColVal = self.treeView.item(node)["text"]
            if self.treeColIsInt: 
                return int(treeColVal)
        else:
            treeColVal = self.treeView.set(node, col)
            if col == "sequence":
                try:
                    return int(treeColVal)
                except:
                    return 0
        return treeColVal
    
    def sortNestedRows(self, parentNode, col, reverse):
        l = [(self.colSortVal(node, col), node) for node in self.treeView.get_children(parentNode)]
        l.sort(reverse=reverse)
        # rearrange items in sorted positions     
        for i, (cell, node) in enumerate(l):         
            self.treeView.move(node, parentNode, i)
        # reset even/odd tags
        for i, node in enumerate(self.treeView.get_children(parentNode)):
            self.treeView.item(node, tags=('even' if i & 1 else 'odd',))
            self.sortNestedRows(node, col, reverse)
                    
    def sortColumn(self, col):
        if col == self.lastSortColumn:
            reverse = self.lastSortColumnForward
            self.lastSortColumnForward = not reverse
        else:
            if self.lastSortColumn:
                self.treeView.heading(self.lastSortColumn, image=self.sortImages[2])
            reverse = False
            self.lastSortColumnForward = True
            self.lastSortColumn = col
        self.treeView.heading(col, image=self.sortImages[reverse])
        self.sortNestedRows('', col, reverse)
        self.viewSelectionChange()  # reselect selected rows
        
    def copyCellToClipboard(self, *ignore):
        self.modelXbrl.modelManager.cntlr.clipboardData(
            text=self.treeView.item(self.menuRow)['text'] if self.menuCol == '#0' else self.treeView.set(self.menuRow,self.menuCol))
        
    def copyRowToClipboard(self, *ignore):
        self.modelXbrl.modelManager.cntlr.clipboardData(
            text='\t'.join([self.treeView.item(self.menuRow)['text']] +
                           [self.treeView.set(self.menuRow,c) for c in self.treeView['columns']]))
        
    def copyTableToClipboard(self, *ignore):
        cols = self.treeView['columns']
        lines = ['\t'.join([self.treeView.heading('#0')['text']] +
                           [self.treeView.heading(h)['text'] for h in cols])]
        self.tabLines('', '', cols, lines)
        self.modelXbrl.modelManager.cntlr.clipboardData(text='\n'.join(lines))

    def tabLines(self, parentNode, indent, cols, lines): 
        for node in self.treeView.get_children(parentNode):
            lines.append('\t'.join([indent + self.treeView.item(node)['text']] +
                                   [self.treeView.set(node,c) for c in cols]))
            self.tabLines(node, indent+'    ', cols, lines)

    def onDoubleClick(self, event):
        ''' Executed, when a row is double-clicked. Opens 
        a EntryPopup above the item's column, so it is possible
        to edit the text '''
        # do nothing if no column is editable
        if len(self.editableColumns)<=0:
            return
        
        # delete any open Entry Popup
        if self.entryPopup:
            self.entryPopup.destroy()
            self.entryPopup = None

        # what row and column was clicked on
        rowID = self.treeView.identify_row(event.y)
        column = self.treeView.identify_column(event.x)

        if not (column in self.editableColumns and (self.treeView.tag_has("editable", rowID))):
            return

        # get column position info
        x,y,width,height = self.treeView.bbox(rowID, column)
    
        # y-axis offset
        pady = height // 2
    
        # place Entry popup properly
        data = self.treeView.set(rowID, column=column)
        self.entryPopup = EntryPopup(self.treeView, rowID, column, data, self.valueChanged)
        self.entryPopup.place( x=x, y=y+pady, anchor=W, relwidth=1)
        
    def valueChanged(self, rowID, column, value):
        if self.valueChangedCallback is not None:
            self.valueChangedCallback(rowID, column, value)
Beispiel #17
0
    def __init__(self, mainWin, options):
        self.mainWin = mainWin
        parent = mainWin.parent
        super(DialogRssWatch, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("RSS Feed Processing Control"))

        frame = Frame(self)
        frame.focus_set()

        # checkbox entries
        row = 1  # row number (to allow future plugins
        label(frame, 1, row, "RSS Feed:")
        feedSources = sorted(rssFeeds.keys())
        self.cellFeed = gridCombobox(frame,
                                     2,
                                     row,
                                     options.get("feedSource", ""),
                                     values=feedSources)
        self.cellFeed.grid(pady=2)
        ToolTip(
            self.cellFeed,
            text=
            _("Select an RSS feed to process for item matching, formulas, and validations as selected below"
              ),
            wraplength=240)
        row += 1
        label(frame, 1, row, "Match fact text:")
        self.cellMatchText = gridCell(frame, 2, row,
                                      options.get("matchTextExpr", ""))
        ToolTip(
            self.cellMatchText,
            text=
            _("Enter a regular expression to be matched to the text of each filing instance fact item. "
              "Regular expressions may contain patterns to detect, such as ab.?c, for any single character between b and c, or ab.*c for any number of characters between b and c."
              ),
            wraplength=240)
        row += 1
        label(frame, 1, row, "Formula file:")
        self.cellFormulaFile = gridCell(frame, 2, row,
                                        options.get("formulaFileUri", ""))
        ToolTip(
            self.cellFormulaFile,
            text=
            _("Select a formula linkbase to to evaluate each filing.  "
              "The formula linkbase may contain one or more assertions, the results of which is recorded in the log file.  "
              "If unsuccessful assertion alerts are selected and an e-mail address provided, the recipient will be notified of filings with assertions that do not pass."
              ),
            wraplength=240)
        openFileImage = PhotoImage(
            file=os.path.join(mainWin.imagesDir, "toolbarOpenFile.gif"))
        chooseFormulaFileButton = Button(frame,
                                         image=openFileImage,
                                         width=12,
                                         command=self.chooseFormulaFile)
        chooseFormulaFileButton.grid(row=row, column=3, sticky=W)
        row += 1
        openDatabaseImage = PhotoImage(
            file=os.path.join(mainWin.imagesDir, "toolbarOpenDatabase.gif"))
        for pluginXbrlMethod in pluginClassMethods(
                "DialogRssWatch.FileChoices"):
            pluginXbrlMethod(self, frame, row, options, mainWin, openFileImage,
                             openDatabaseImage)
            row += 1
        label(frame, 1, row, "Log file:")
        self.cellLogFile = gridCell(frame, 2, row,
                                    options.get("logFileUri", ""))
        ToolTip(
            self.cellLogFile,
            text=
            _("Select a log file in which to save an activity log, including validation results, matched item text, and formula results.\n\n "
              "If file ends in .xml it is xml-formatted, otherwise it is text. "
              ),
            wraplength=240)
        chooseLogFileButton = Button(frame,
                                     image=openFileImage,
                                     width=12,
                                     command=self.chooseLogFile)
        chooseLogFileButton.grid(row=row, column=3, sticky=W)
        row += 1
        label(frame, 1, row, "E-mail alerts to:")
        self.cellEmailAddress = gridCell(frame, 2, row,
                                         options.get("emailAddress", ""))
        ToolTip(self.cellEmailAddress,
                text=_("Specify e-mail recipient(s) for alerts per below."),
                wraplength=240)
        propertiesImage = PhotoImage(
            file=os.path.join(mainWin.imagesDir, "toolbarProperties.gif"))
        smtpSetupButton = Button(frame,
                                 image=propertiesImage,
                                 width=12,
                                 command=self.setupSmtp)
        smtpSetupButton.grid(row=row, column=3, sticky=W)
        ToolTip(
            smtpSetupButton,
            text=_("Enter/edit settings of outgoing e-mail server (SMTP)."),
            wraplength=240)
        row += 1
        label(frame, 1, row, "Latest pub date:")
        pubdate = getattr(options, "latestPubDate", None)
        self.cellLatestPubDate = gridCell(frame, 2, row,
                                          str(pubdate) if pubdate else "")
        ToolTip(
            self.cellLatestPubDate,
            text=
            _("Specify pub dateTime of last processed submission.  Next item to examine will be after this dateTime."
              ),
            wraplength=240)
        clearImage = PhotoImage(
            file=os.path.join(mainWin.imagesDir, "toolbarDelete.gif"))
        clearPubDateButton = Button(frame,
                                    image=clearImage,
                                    width=12,
                                    command=self.clearPubDate)
        clearPubDateButton.grid(row=row, column=3, sticky=W)
        ToolTip(
            clearPubDateButton,
            text=
            _("Clear pub dateTime so that next cycle processes all entries in RSS feed."
              ),
            wraplength=240)
        row += 1
        label(frame, 2, row, "Validate:")
        row += 1
        self.checkboxes = (
            checkbox(frame, 2, row, "XBRL 2.1 and Dimensions rules",
                     "validateXbrlRules"),
            checkbox(frame, 2, row + 1, "Selected disclosure system rules",
                     "validateDisclosureSystemRules"),
            checkbox(frame, 2, row + 2, "Calculation linkbase roll-up",
                     "validateCalcLinkbase"),
            checkbox(frame, 2, row + 3, "Formula assertions",
                     "validateFormulaAssertions"),
            # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync
        )
        row += 4
        for pluginXbrlMethod in pluginClassMethods(
                "DialogRssWatch.ValidateChoices"):
            pluginXbrlMethod(self, frame, row, options, mainWin)
            row += 1
        label(frame, 2, row, "Alert on:")
        row += 1
        self.checkboxes += (
            checkbox(frame, 2, row, "Facts with matching text",
                     "alertMatchedFactText"),
            checkbox(frame, 2, row + 1, "Unsuccessful formula assertions",
                     "alertAssertionUnsuccessful"),
            checkbox(frame, 2, row + 2, "Validation errors",
                     "alertValiditionError"),
            # Note: if adding to this list keep ModelFormulaObject.FormulaOptions in sync
        )
        row += 3

        mainWin.showStatus(None)

        cancelButton = Button(frame,
                              text=_("Cancel"),
                              width=8,
                              command=self.close)
        ToolTip(cancelButton,
                text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=row,
                          column=1,
                          columnspan=3,
                          sticky=E,
                          pady=3,
                          padx=3)
        okButton.grid(row=row,
                      column=1,
                      columnspan=3,
                      sticky=E,
                      pady=3,
                      padx=86)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #18
0
    def __init__(self,
                 mainWin,
                 openType,
                 filesource,
                 filenames,
                 title,
                 colHeader,
                 showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            metadata = filesource.file(filesource.url + os.sep +
                                       TAXONOMY_PACKAGE_FILE_NAME)[0]

            try:
                self.nameToUrls = parseTxmyPkg(mainWin, metadata)
            except Exception as e:
                self.close()
                err = _(
                    "Failed to parse metadata; the underlying error was: {0}"
                ).format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return

        mainWin.showStatus(None)

        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        if showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y,
                                    column=0,
                                    sticky=(S, W),
                                    pady=3,
                                    padx=3)

        self.loadTreeView(openType, colHeader, title)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #19
0
    def __init__(self, mainWin, modulesWithNewerFileDates):
        super(DialogPluginManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.pluginConfig = PluginManager.pluginConfig
        self.pluginConfigChanged = False
        self.uiClassMethodsChanged = False
        self.modelClassesChanged = False
        self.disclosureSystemTypesChanged = False
        self.modulesWithNewerFileDates = modulesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Plug-in Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find plug-in modules:"), wraplength=60, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting python module files to add (or reload) plug-ins, from the local file system."), wraplength=240)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) plug-ins, from the web or local file system."), wraplength=240)
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=2, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (plugins already known to arelle)
        modulesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(modulesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(modulesFrame, orient=HORIZONTAL)
        self.modulesView = Treeview(modulesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.modulesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.modulesView.bind('<<TreeviewSelect>>', self.moduleSelect)
        hScrollbar["command"] = self.modulesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.modulesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        modulesFrame.columnconfigure(0, weight=1)
        modulesFrame.rowconfigure(0, weight=1)
        modulesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.modulesView.focus_set()

        self.modulesView.column("#0", width=120, anchor="w")
        self.modulesView.heading("#0", text=_("Name"))
        self.modulesView["columns"] = ("author", "ver", "status", "date", "update", "descr", "license")
        self.modulesView.column("author", width=100, anchor="w", stretch=False)
        self.modulesView.heading("author", text=_("Author"))
        self.modulesView.column("ver", width=50, anchor="w", stretch=False)
        self.modulesView.heading("ver", text=_("Version"))
        self.modulesView.column("status", width=50, anchor="w", stretch=False)
        self.modulesView.heading("status", text=_("Status"))
        self.modulesView.column("date", width=70, anchor="w", stretch=False)
        self.modulesView.heading("date", text=_("File Date"))
        self.modulesView.column("update", width=50, anchor="w", stretch=False)
        self.modulesView.heading("update", text=_("Update"))
        self.modulesView.column("descr", width=200, anchor="w", stretch=False)
        self.modulesView.heading("descr", text=_("Description"))
        self.modulesView.column("license", width=70, anchor="w", stretch=False)
        self.modulesView.heading("license", text=_("License"))

        classesFrame = Frame(frame)
        vScrollbar = Scrollbar(classesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(classesFrame, orient=HORIZONTAL)
        self.classesView = Treeview(classesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.classesView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.classesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.classesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        classesFrame.columnconfigure(0, weight=1)
        classesFrame.rowconfigure(0, weight=1)
        classesFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.classesView.focus_set()
        
        self.classesView.column("#0", width=200, anchor="w")
        self.classesView.heading("#0", text=_("Class"))
        self.classesView["columns"] = ("modules",)
        self.classesView.column("modules", width=500, anchor="w", stretch=False)
        self.classesView.heading("modules", text=_("Modules"))
        
        # bottom frame module info details
        moduleInfoFrame = Frame(frame, width=700)
        moduleInfoFrame.columnconfigure(1, weight=1)
        
        self.moduleNameLabel = Label(moduleInfoFrame, wraplength=600, justify="left", 
                                     font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.moduleNameLabel.grid(row=0, column=0, columnspan=4, sticky=W)
        self.moduleAuthorHdr = Label(moduleInfoFrame, text=_("author:"), state=DISABLED)
        self.moduleAuthorHdr.grid(row=1, column=0, sticky=W)
        self.moduleAuthorLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleAuthorLabel.grid(row=1, column=1, columnspan=3, sticky=W)
        self.moduleDescrHdr = Label(moduleInfoFrame, text=_("description:"), state=DISABLED)
        self.moduleDescrHdr.grid(row=2, column=0, sticky=W)
        self.moduleDescrLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDescrLabel.grid(row=2, column=1, columnspan=3, sticky=W)
        self.moduleClassesHdr = Label(moduleInfoFrame, text=_("classes:"), state=DISABLED)
        self.moduleClassesHdr.grid(row=3, column=0, sticky=W)
        self.moduleClassesLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleClassesLabel.grid(row=3, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleClassesLabel, text=_("List of classes that this plug-in handles."), wraplength=240)
        self.moduleUrlHdr = Label(moduleInfoFrame, text=_("URL:"), state=DISABLED)
        self.moduleUrlHdr.grid(row=4, column=0, sticky=W)
        self.moduleUrlLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleUrlLabel.grid(row=4, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleUrlLabel, text=_("URL of plug-in module (local file path or web loaded file)."), wraplength=240)
        self.moduleDateHdr = Label(moduleInfoFrame, text=_("date:"), state=DISABLED)
        self.moduleDateHdr.grid(row=5, column=0, sticky=W)
        self.moduleDateLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleDateLabel.grid(row=5, column=1, columnspan=3, sticky=W)
        ToolTip(self.moduleDateLabel, text=_("Date of currently loaded module file (with parenthetical node when an update is available)."), wraplength=240)
        self.moduleLicenseHdr = Label(moduleInfoFrame, text=_("license:"), state=DISABLED)
        self.moduleLicenseHdr.grid(row=6, column=0, sticky=W)
        self.moduleLicenseLabel = Label(moduleInfoFrame, wraplength=600, justify="left")
        self.moduleLicenseLabel.grid(row=6, column=1, columnspan=3, sticky=W)
        self.moduleEnableButton = Button(moduleInfoFrame, text=self.ENABLE, state=DISABLED, command=self.moduleEnable)
        ToolTip(self.moduleEnableButton, text=_("Enable/disable plug in."), wraplength=240)
        self.moduleEnableButton.grid(row=7, column=1, sticky=E)
        self.moduleReloadButton = Button(moduleInfoFrame, text=_("Reload"), state=DISABLED, command=self.moduleReload)
        ToolTip(self.moduleReloadButton, text=_("Reload/update plug in."), wraplength=240)
        self.moduleReloadButton.grid(row=7, column=2, sticky=E)
        self.moduleRemoveButton = Button(moduleInfoFrame, text=_("Remove"), state=DISABLED, command=self.moduleRemove)
        ToolTip(self.moduleRemoveButton, text=_("Remove plug in from plug in table (does not erase the plug in's file)."), wraplength=240)
        self.moduleRemoveButton.grid(row=7, column=3, sticky=E)
        moduleInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        moduleInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        enableDisableFrame = Frame(frame)
        enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3)
        enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll)
        ToolTip(enableAllButton, text=_("Enable all plug ins."), wraplength=240)
        disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll)
        ToolTip(disableAllButton, text=_("Disable all plug ins."), wraplength=240)
        enableAllButton.grid(row=1, column=1)
        disableAllButton.grid(row=1, column=2)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #20
0
class DialogOpenArchive(Toplevel):
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                if len(metadataFiles) > 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                metadataFile = metadataFiles[0]
                metadata = filesource.file(filesource.url + os.sep + metadataFile)[0]
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += os.sep
        
                self.nameToUrls, self.remappings = parseTxmyPkg(mainWin, metadata)
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return
    
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
        
    def loadTreeView(self, openType, title, colHeader):
        self.title(title)
        self.openType = openType
        selectedNode = None

        # clear previous treeview entries
        for previousNode in self.treeView.get_children(""): 
            self.treeView.delete(previousNode)

        # set up treeView widget and tabbed pane
        if openType in (ARCHIVE, DISCLOSURE_SYSTEM):
            self.treeView.column("#0", width=500, anchor="w")
            self.treeView.heading("#0", text=colHeader)
            try:
                self.isRss = self.filesource.isRss
                if self.isRss:
                    self.treeView.column("#0", width=350, anchor="w")
                    self.treeView["columns"] = ("descr", "date", "instDoc")
                    self.treeView.column("descr", width=50, anchor="center", stretch=False)
                    self.treeView.heading("descr", text="Form")
                    self.treeView.column("date", width=170, anchor="w", stretch=False)
                    self.treeView.heading("date", text="Pub Date")
                    self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
                    self.treeView.heading("instDoc", text="Instance Document")
            except AttributeError:
                self.isRss = False
                self.treeView["columns"] = tuple()
        
            loadedPaths = []
            for i, filename in enumerate(self.filenames):
                if isinstance(filename,tuple):
                    if self.isRss:
                        form, date, instDoc = filename[2:5]
                    filename = filename[0] # ignore tooltip
                    self.hasToolTip = True
                if filename.endswith("/"):
                    filename = filename[:-1]
                path = filename.split("/")
                if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                    parent = "file{0}".format(loadedPaths.index(path[:-1]))
                else:
                    parent = "" 
                node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc", os.path.basename(instDoc))
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=150, anchor="w")
            self.treeView.heading("#0", text="Name")
    
            self.treeView["columns"] = ("url",)
            self.treeView.column("url", width=350, anchor="w")
            self.treeView.heading("url", text="URL")
            
            for name, urls in self.nameToUrls.items():
                displayUrl = urls[1] # display the canonical URL
                self.treeView.insert("", "end", name, values=[displayUrl], text=name)
                
            self.hasToolTip = True
        else: # unknown openType
            return None
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)

        if self.showAltViewButton:
            self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries"))

        
    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                filename = self.filenames[int(selection[0][4:])]
                if isinstance(filename,tuple):
                    if self.isRss:
                        filename = filename[4]
                    else:
                        filename = filename[0]
                if not filename.endswith("/"):
                    self.filesource.select(filename)
                    self.accepted = True
                    self.close()
            elif self.openType == ENTRY_POINTS:
                epName = selection[0]
                #index 0 is the remapped Url, as opposed to the canonical one used for display
                urlOrFile = self.nameToUrls[epName][0]
                
                # load file source remappings
                self.filesource.mappedPaths = \
                    dict((prefix, 
                          remapping if isHttpUrl(remapping)
                          else (self.filesource.baseurl + os.sep + self.metadataFilePrefix +remapping.replace("/", os.sep)))
                          for prefix, remapping in self.remappings.items())
    
                if not urlOrFile.endswith("/"):
                    # check if it's an absolute URL rather than a path into the archive
                    if isHttpUrl(urlOrFile):
                        self.filesource.select(urlOrFile)  # absolute path selection
                    else:
                        # assume it's a path inside the archive:
                        self.filesource.select(self.metadataFilePrefix + urlOrFile)
                    self.accepted = True
                    self.close()
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
        
    def showAltView(self, event=None):
        if self.openType == ENTRY_POINTS:
            self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File"))
        else:
            self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File"))
        
    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvRowId != self.toolTipRowId:
            text = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                self.toolTipRowId = tvRowId
                if tvRowId and len(tvRowId) > 4:
                    try:
                        text = self.filenames[ int(tvRowId[4:]) ]
                        if isinstance(text, tuple):
                            text = text[1].replace("\\n","\n")
                    except (KeyError, ValueError):
                        pass
            elif self.openType == ENTRY_POINTS:
                try:
                    epUrl = self.nameToUrls[tvRowId][1]
                    text = "{0}\n{1}".format(tvRowId, epUrl)
                except KeyError:
                    pass
            self.setToolTip(text)
                
    def setToolTip(self, text):
        self.toolTip._hide()
        if text:
            self.toolTipText.set(text)
            self.toolTip.configure(state="normal")
            self.toolTip._schedule()
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")
Beispiel #21
0
 def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False, lang=None, editableColumns=[], valueChangedCallback=None):
     self.tabWin = tabWin
     self.viewFrame = Frame(tabWin)
     self.viewFrame.view = self
     self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
     tabWin.add(self.viewFrame,text=tabTitle)
     self.tabTitle = tabTitle # for error messages
     vScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
     hScrollbar = Scrollbar(self.viewFrame, orient=HORIZONTAL)
     self.isEbaTableIndex = False
     if tabTitle.startswith('Tables'):
         for pluginXbrlMethod in pluginClassMethods("CntlrWinMain.Modeling.LoadFilingIndicators"):
             self.isEbaTableIndex = True
             # for EBA and in case of table index, add a second column with the filing indicator
             # (OK, it is not really sound to base this test on the title)            
             self.treeView = Treeview(self.viewFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, columns="Filing")
             break
     if not self.isEbaTableIndex:
         self.treeView = Treeview(self.viewFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
     self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
     self.treeView.tag_configure("ELR", background="#E0F0FF")
     self.treeView.tag_configure("even", background="#F0F0F0")
     self.treeView.tag_configure("odd", background="#FFFFFF")
     if modelXbrl.modelManager.cntlr.isMac or modelXbrl.modelManager.cntlr.isMSW:
         highlightColor = "#%04x%04x%04x" % self.treeView.winfo_rgb("SystemHighlight")
     else:
         highlightColor = "#33339999ffff"  # using MSW value for Unix/Linux which has no named colors
     self.treeView.tag_configure("selected-ELR", background=highlightColor)
     self.treeView.tag_configure("selected-even", background=highlightColor)
     self.treeView.tag_configure("selected-odd", background=highlightColor)
     self.treeViewSelection = ()
     self.treeView.bind("<<TreeviewSelect>>", self.viewSelectionChange, '+')
     self.treeView.bind("<1>", self.onViewClick, '+')
     self.treeView.bind("<Double-1>", self.onDoubleClick, '+')
     hScrollbar["command"] = self.treeView.xview
     hScrollbar.grid(row=1, column=0, sticky=(E,W))
     vScrollbar["command"] = self.treeView.yview
     vScrollbar.grid(row=0, column=1, sticky=(N,S))
     self.viewFrame.columnconfigure(0, weight=1)
     self.viewFrame.rowconfigure(0, weight=1)
     self.modelXbrl = modelXbrl
     self.hasToolTip = hasToolTip
     self.toolTipText = StringVar()
     if hasToolTip:
         self.treeView.bind("<Motion>", self.motion, '+')
         self.treeView.bind("<Leave>", self.leave, '+')
         self.toolTipText = StringVar()
         self.toolTip = ToolTip(self.treeView, 
                                textvariable=self.toolTipText, 
                                wraplength=480, 
                                follow_mouse=True,
                                state="disabled")
         self.toolTipColId = None
         self.toolTipRowId = None
     self.modelXbrl = modelXbrl
     self.lang = lang
     self.labelrole = None
     self.nameIsPrefixed = False
     if modelXbrl:
         modelXbrl.views.append(self)
         if not lang: 
             self.lang = modelXbrl.modelManager.defaultLang
     self.editableColumns = editableColumns
     self.valueChangedCallback = valueChangedCallback
     self.entryPopup = None
Beispiel #22
0
    def __init__(self, mainWin, packageNamesWithNewerFileDates):
        super(DialogPackageManager, self).__init__(mainWin.parent)
        
        self.ENABLE = _("Enable")
        self.DISABLE = _("Disable")
        self.parent = mainWin.parent
        self.cntlr = mainWin
        
        # copy plugins for temporary display
        self.packagesConfig = PackageManager.packagesConfig
        self.packagesConfigChanged = False
        self.packageNamesWithNewerFileDates = packageNamesWithNewerFileDates
        
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", self.parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))

        self.title(_("Taxonomy Packages Manager"))
        frame = Frame(self)
        
        # left button frame
        buttonFrame = Frame(frame, width=40)
        buttonFrame.columnconfigure(0, weight=1)
        addLabel = Label(buttonFrame, text=_("Find taxonomy packages:"), wraplength=64, justify="center")
        addLocalButton = Button(buttonFrame, text=_("Locally"), command=self.findLocally)
        ToolTip(addLocalButton, text=_("File chooser allows selecting taxonomy packages to add (or reload), from the local file system.  "
                                       "Select either a PWD or prior taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=360)
        addWebButton = Button(buttonFrame, text=_("On Web"), command=self.findOnWeb)
        ToolTip(addWebButton, text=_("Dialog to enter URL full path to load (or reload) package, from the web or local file system.  "
                                     "URL may be either a PWD or prior taxonomy package zip file, or a taxonomy manifest (.taxonomyPackage.xml) within an unzipped taxonomy package.  "), wraplength=360)
        manifestNameButton = Button(buttonFrame, text=_("Manifest"), command=self.manifestName)
        ToolTip(manifestNameButton, text=_("Provide pre-PWD non-standard archive manifest file name pattern (e.g., *taxonomyPackage.xml).  "
                                           "Uses unix file name pattern matching.  "
                                           "Multiple manifest files are supported in pre-PWD archives (such as oasis catalogs).  "
                                           "(Replaces pre-PWD search for either .taxonomyPackage.xml or catalog.xml).  "), wraplength=480)
        self.manifestNamePattern = ""
        addLabel.grid(row=0, column=0, pady=4)
        addLocalButton.grid(row=1, column=0, pady=4)
        addWebButton.grid(row=2, column=0, pady=4)
        manifestNameButton.grid(row=3, column=0, pady=4)
        buttonFrame.grid(row=0, column=0, rowspan=3, sticky=(N, S, W), padx=3, pady=3)
        
        # right tree frame (packages already known to arelle)
        packagesFrame = Frame(frame, width=700)
        vScrollbar = Scrollbar(packagesFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(packagesFrame, orient=HORIZONTAL)
        self.packagesView = Treeview(packagesFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=7)
        self.packagesView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.packagesView.bind('<<TreeviewSelect>>', self.packageSelect)
        hScrollbar["command"] = self.packagesView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.packagesView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        packagesFrame.columnconfigure(0, weight=1)
        packagesFrame.rowconfigure(0, weight=1)
        packagesFrame.grid(row=0, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.packagesView.focus_set()

        self.packagesView.column("#0", width=120, anchor="w")
        self.packagesView.heading("#0", text=_("Name"))
        self.packagesView["columns"] = ("ver", "status", "date", "update", "descr")
        self.packagesView.column("ver", width=150, anchor="w", stretch=False)
        self.packagesView.heading("ver", text=_("Version"))
        self.packagesView.column("status", width=50, anchor="w", stretch=False)
        self.packagesView.heading("status", text=_("Status"))
        self.packagesView.column("date", width=170, anchor="w", stretch=False)
        self.packagesView.heading("date", text=_("File Date"))
        self.packagesView.column("update", width=50, anchor="w", stretch=False)
        self.packagesView.heading("update", text=_("Update"))
        self.packagesView.column("descr", width=200, anchor="w", stretch=False)
        self.packagesView.heading("descr", text=_("Description"))

        remappingsFrame = Frame(frame)
        vScrollbar = Scrollbar(remappingsFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(remappingsFrame, orient=HORIZONTAL)
        self.remappingsView = Treeview(remappingsFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, height=5)
        self.remappingsView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.remappingsView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.remappingsView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        remappingsFrame.columnconfigure(0, weight=1)
        remappingsFrame.rowconfigure(0, weight=1)
        remappingsFrame.grid(row=1, column=1, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.remappingsView.focus_set()
        
        self.remappingsView.column("#0", width=200, anchor="w")
        self.remappingsView.heading("#0", text=_("Prefix"))
        self.remappingsView["columns"] = ("remapping")
        self.remappingsView.column("remapping", width=500, anchor="w", stretch=False)
        self.remappingsView.heading("remapping", text=_("Remapping"))
        
        # bottom frame package info details
        packageInfoFrame = Frame(frame, width=700)
        packageInfoFrame.columnconfigure(1, weight=1)
        
        self.packageNameLabel = Label(packageInfoFrame, wraplength=600, justify="left", 
                                      font=font.Font(family='Helvetica', size=12, weight='bold'))
        self.packageNameLabel.grid(row=0, column=0, columnspan=6, sticky=W)
        self.packageVersionHdr = Label(packageInfoFrame, text=_("version:"), state=DISABLED)
        self.packageVersionHdr.grid(row=1, column=0, sticky=W)
        self.packageVersionLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageVersionLabel.grid(row=1, column=1, columnspan=5, sticky=W)
        self.packageDescrHdr = Label(packageInfoFrame, text=_("description:"), state=DISABLED)
        self.packageDescrHdr.grid(row=2, column=0, sticky=W)
        self.packageDescrLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDescrLabel.grid(row=2, column=1, columnspan=5, sticky=W)
        self.packagePrefixesHdr = Label(packageInfoFrame, text=_("prefixes:"), state=DISABLED)
        self.packagePrefixesHdr.grid(row=3, column=0, sticky=W)
        self.packagePrefixesLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packagePrefixesLabel.grid(row=3, column=1, columnspan=5, sticky=W)
        ToolTip(self.packagePrefixesLabel, text=_("List of prefixes that this package remaps."), wraplength=240)
        self.packageUrlHdr = Label(packageInfoFrame, text=_("URL:"), state=DISABLED)
        self.packageUrlHdr.grid(row=4, column=0, sticky=W)
        self.packageUrlLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageUrlLabel.grid(row=4, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageUrlLabel, text=_("URL of taxonomy package (local file path or web loaded file)."), wraplength=240)
        self.packageDateHdr = Label(packageInfoFrame, text=_("date:"), state=DISABLED)
        self.packageDateHdr.grid(row=5, column=0, sticky=W)
        self.packageDateLabel = Label(packageInfoFrame, wraplength=600, justify="left")
        self.packageDateLabel.grid(row=5, column=1, columnspan=5, sticky=W)
        ToolTip(self.packageDateLabel, text=_("Date of currently loaded package file (with parenthetical node when an update is available)."), wraplength=240)
        self.packageEnableButton = Button(packageInfoFrame, text=self.ENABLE, state=DISABLED, command=self.packageEnable)
        ToolTip(self.packageEnableButton, text=_("Enable/disable package."), wraplength=240)
        self.packageEnableButton.grid(row=6, column=1, sticky=E)
        self.packageMoveUpButton = Button(packageInfoFrame, text=_("Move Up"), state=DISABLED, command=self.packageMoveUp)
        ToolTip(self.packageMoveUpButton, text=_("Move package up (above other remappings)."), wraplength=240)
        self.packageMoveUpButton.grid(row=6, column=2, sticky=E)
        self.packageMoveDownButton = Button(packageInfoFrame, text=_("Move Down"), state=DISABLED, command=self.packageMoveDown)
        ToolTip(self.packageMoveDownButton, text=_("Move package down (below other remappings)."), wraplength=240)
        self.packageMoveDownButton.grid(row=6, column=3, sticky=E)
        self.packageReloadButton = Button(packageInfoFrame, text=_("Reload"), state=DISABLED, command=self.packageReload)
        ToolTip(self.packageReloadButton, text=_("Reload/update package."), wraplength=240)
        self.packageReloadButton.grid(row=6, column=4, sticky=E)
        self.packageRemoveButton = Button(packageInfoFrame, text=_("Remove"), state=DISABLED, command=self.packageRemove)
        ToolTip(self.packageRemoveButton, text=_("Remove package from packages table (does not erase the package file)."), wraplength=240)
        self.packageRemoveButton.grid(row=6, column=5, sticky=E)
        packageInfoFrame.grid(row=2, column=0, columnspan=5, sticky=(N, S, E, W), padx=3, pady=3)
        packageInfoFrame.config(borderwidth=4, relief="groove")
        
        okButton = Button(frame, text=_("Close"), command=self.ok)
        ToolTip(okButton, text=_("Accept and changes (if any) and close dialog."), wraplength=240)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        ToolTip(cancelButton, text=_("Cancel changes (if any) and close dialog."), wraplength=240)
        okButton.grid(row=3, column=3, sticky=(S,E), pady=3)
        cancelButton.grid(row=3, column=4, sticky=(S,E), pady=3, padx=3)
        
        enableDisableFrame = Frame(frame)
        enableDisableFrame.grid(row=3, column=1, sticky=(S,W), pady=3)
        enableAllButton = Button(enableDisableFrame, text=_("Enable All"), command=self.enableAll)
        ToolTip(enableAllButton, text=_("Enable all packages."), wraplength=240)
        disableAllButton = Button(enableDisableFrame, text=_("Disable All"), command=self.disableAll)
        ToolTip(disableAllButton, text=_("Disable all packages."), wraplength=240)
        enableAllButton.grid(row=1, column=1)
        disableAllButton.grid(row=1, column=2)
        
        self.loadTreeViews()

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=0)
        frame.columnconfigure(1, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #23
0
class ViewList():
    def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False):
        self.tabWin = tabWin
        self.viewFrame = Frame(tabWin)
        self.viewFrame.view = self
        self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        tabWin.add(self.viewFrame, text=tabTitle)
        xmlScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
        self.listBox = Listbox(self.viewFrame, yscrollcommand=xmlScrollbar.set)
        self.listBox.grid(row=0, column=0, sticky=(N, S, E, W))
        #self.listBox.focus_set()
        self.listBox.bind("<Motion>", self.listBoxMotion, '+')
        self.listBox.bind("<1>", self.listBoxClick, '+')
        self.listBox.bind("<Leave>", self.listBoxLeave, '+')
        xmlScrollbar["command"] = self.listBox.yview
        xmlScrollbar.grid(row=0, column=1, sticky=(N, S))
        self.viewFrame.columnconfigure(0, weight=1)
        self.viewFrame.rowconfigure(0, weight=1)
        self.listBoxToolTipText = StringVar()
        if hasToolTip:
            self.listBoxToolTip = ToolTip(self.listBox,
                                          textvariable=self.listBoxToolTipText,
                                          wraplength=480,
                                          follow_mouse=True,
                                          state="disabled")
            self.listBoxRow = -9999999
        self.modelXbrl = modelXbrl
        if modelXbrl:
            modelXbrl.views.append(self)

    def close(self):
        del self.viewFrame.view
        self.tabWin.forget(self.viewFrame)
        self.modelXbrl.views.remove(self)
        self.modelXbrl = None

    def select(self):
        self.tabWin.select(self.viewFrame)

    def append(self, line):
        self.listBox.insert(END, line)

    def clear(self):
        self.listBox.delete(0, END)

    def listBoxClick(self, *args):
        if self.modelXbrl:
            self.modelXbrl.modelManager.cntlr.currentView = self

    def listBoxLeave(self, *args):
        self.listBoxRow = -9999999

    def lines(self):
        return self.listBox.get(0, END)

    def lineText(self, lineNumber):
        return self.listBox.get(lineNumber)

    def selectLine(self, lineNumber):
        self.listBox.selection_clear(0, END)
        self.listBox.selection_set(lineNumber)

    def saveToFile(self, filename):
        with open(filename, "w") as fh:
            fh.writelines(
                [logEntry + '\n' for logEntry in self.listBox.get(0, END)])

    def copyToClipboard(self, cntlr=None, *ignore):
        if cntlr is None: cntlr = self.modelXbrl.modelManager.cntlr
        cntlr.clipboardData(text='\n'.join(self.listBox.get(0, END)))

    def listBoxMotion(self, *args):
        lbRow = self.listBox.nearest(args[0].y)
        if lbRow != self.listBoxRow:
            self.listBoxRow = lbRow
            text = self.listBox.get(lbRow)
            self.listBoxToolTip._hide()
            if text and len(text) > 0:
                if len(text) * 8 > 200:
                    self.listBoxToolTipText.set(
                        text[:2048] + "..." if len(text) > 2048 else text)
                    self.listBoxToolTip.configure(state="normal")
                    self.listBoxToolTip._schedule()
                else:
                    self.listBoxToolTipText.set("")
                    self.listBoxToolTip.configure(state="disabled")
            else:
                self.listBoxToolTipText.set("")
                self.listBoxToolTip.configure(state="disabled")

    def contextMenu(self, contextMenuClick=None):
        try:
            return self.menu
        except AttributeError:
            if contextMenuClick is None:
                contextMenuClick = self.modelXbrl.modelManager.cntlr.contextMenuClick
            self.menu = Menu(self.viewFrame, tearoff=0)
            self.listBox.bind(contextMenuClick, self.popUpMenu)
            return self.menu

    def popUpMenu(self, event):
        self.menu.post(event.x_root, event.y_root)

    def menuAddSaveClipboard(self):
        self.menu.add_command(
            label=_("Save to file"),
            underline=0,
            command=self.modelXbrl.modelManager.cntlr.fileSave)
        if self.modelXbrl.modelManager.cntlr.hasClipboard:
            self.menu.add_command(label=_("Copy to clipboard"),
                                  underline=0,
                                  command=self.copyToClipboard)
    def __init__(self, mainWin, openType, filesource, filenames, title):
        parent = mainWin.parent
        super().__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.webUrl = None

        self.transient(self.parent)
        self.title(title)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, columns=2)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))

        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))

        treeFrame.columnconfigure(0, weight=1)

        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)

        self.treeView.focus_set()

        # set up treeView widget and tabbed pane
        self.treeView.column("#0", width=150, anchor="w")
        self.treeView.heading("#0", text="Name")

        self.treeView.column("#1", width=350, anchor="w")
        self.treeView.heading("#1", text="URL")

        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        selectedNode = None

        metadata = filesource.file(filesource.url + os.sep + TAXONOMY_PACKAGE_FILE_NAME)[0]

        try:
            self.nameToUrls = parseTxmyPkg(mainWin, metadata)
        except Exception as e:
            self.close()
            err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
            messagebox.showerror(_("Malformed taxonomy package"), err)
            mainWin.addToLog(err)
            return

        for name, urls in self.nameToUrls.items():
            displayUrl = urls[1] # display the canonical URL
            self.treeView.insert("", "end", name, values=[displayUrl], text=name)

        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)
        mainWin.showStatus(None)

        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        self.treeView.bind("<Motion>", self.motion, '+')
        self.treeView.bind("<Leave>", self.leave, '+')
        self.toolTipText = StringVar()
        self.toolTip = ToolTip(self.treeView,
                               textvariable=self.toolTipText,
                               wraplength=640,
                               follow_mouse=True,
                               state="disabled")
        self.toolTipEpName = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
class DialogOpenTaxonomyPackage(Toplevel):
    def __init__(self, mainWin, openType, filesource, filenames, title):
        parent = mainWin.parent
        super().__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.webUrl = None

        self.transient(self.parent)
        self.title(title)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set, columns=2)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))

        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))

        treeFrame.columnconfigure(0, weight=1)

        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)

        self.treeView.focus_set()

        # set up treeView widget and tabbed pane
        self.treeView.column("#0", width=150, anchor="w")
        self.treeView.heading("#0", text="Name")

        self.treeView.column("#1", width=350, anchor="w")
        self.treeView.heading("#1", text="URL")

        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        selectedNode = None

        metadata = filesource.file(filesource.url + os.sep + TAXONOMY_PACKAGE_FILE_NAME)[0]

        try:
            self.nameToUrls = parseTxmyPkg(mainWin, metadata)
        except Exception as e:
            self.close()
            err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
            messagebox.showerror(_("Malformed taxonomy package"), err)
            mainWin.addToLog(err)
            return

        for name, urls in self.nameToUrls.items():
            displayUrl = urls[1] # display the canonical URL
            self.treeView.insert("", "end", name, values=[displayUrl], text=name)

        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)
        mainWin.showStatus(None)

        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        self.treeView.bind("<Motion>", self.motion, '+')
        self.treeView.bind("<Leave>", self.leave, '+')
        self.toolTipText = StringVar()
        self.toolTip = ToolTip(self.treeView,
                               textvariable=self.toolTipText,
                               wraplength=640,
                               follow_mouse=True,
                               state="disabled")
        self.toolTipEpName = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)

    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            epName = selection[0]
            #index 0 is the remapped Url, as opposed to the canonical one used for display
            urlOrFile = self.nameToUrls[epName][0]

            if not urlOrFile.endswith("/"):
                # check if it's an absolute URL rather than a path into the archive
                if urlOrFile.startswith("http://") or urlOrFile.startswith("https://"):
                    self.webUrl = urlOrFile
                else:
                    # assume it's a path inside the archive:
                    self.filesource.select(urlOrFile)
                self.accepted = True
                self.close()

    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()

    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        epName = self.treeView.identify_row(args[0].y)
        if epName != self.toolTipEpName:
            self.toolTipEpName = epName
            try:
                epUrl = self.nameToUrls[epName][1]
            except KeyError:
                epUrl = None
            self.toolTip._hide()
            if epName and epUrl:
                self.toolTipText.set("{0}\n{1}".format(epName, epUrl))
                self.toolTip.configure(state="normal")
                self.toolTip._schedule()
            else:
                self.toolTipText.set("")
                self.toolTip.configure(state="disabled")
Beispiel #26
0
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(mainWin, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                # may be a catalog file with no entry oint names
                if not self.taxonomyPackage["nameToUrls"]:
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return
    
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #27
0
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader):
        parent = mainWin.parent
        super().__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(title)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        # set up treeView widget and tabbed pane
        self.treeView.column("#0", width=500, anchor="w")
        self.treeView.heading("#0", text=colHeader)
        try:
            self.isRss = filesource.isRss
            if self.isRss:
                self.treeView.column("#0", width=350, anchor="w")
                self.treeView["columns"] = ("descr", "date", "instDoc")
                self.treeView.column("descr", width=50, anchor="center", stretch=False)
                self.treeView.heading("descr", text="Form")
                self.treeView.column("date", width=170, anchor="w", stretch=False)
                self.treeView.heading("date", text="Pub Date")
                self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
                self.treeView.heading("instDoc", text="Instance Document")
        except AttributeError:
            self.isRss = False
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        selection = filesource.selection
        hasToolTip = False
        loadedPaths = []
        i = 0
        selectedNode = None
        for filename in self.filenames:
            if isinstance(filename,tuple):
                if self.isRss:
                    form, date, instDoc = filename[2:5]
                filename = filename[0] # ignore tooltip
                hasToolTip = True
            if filename.endswith("/"):
                filename = filename[:-1]
            path = filename.split("/")
            if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                parent = "file{0}".format(loadedPaths.index(path[:-1]))
            else:
                parent = "" 
            node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
            if self.isRss:
                self.treeView.set(node, "descr", form)
                self.treeView.set(node, "date", date)
                self.treeView.set(node, "instDoc", os.path.basename(instDoc))
            if selection == filename:
                selectedNode = node
            loadedPaths.append(path)
            i += 1
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #28
0
     def __init__(self, tester):
         self.tester = tester
         self.mainWin = tester.cntlr
 
         parent = self.mainWin.parent
         super(DialogTransformTester, self).__init__(parent)
         self.parent = parent
         parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
         dialogX = int(parentGeometry.group(3))
         dialogY = int(parentGeometry.group(4))
         self.selectedGroup = None
 
         self.transient(self.parent)
         self.title(_("Transformation Tester"))
         
         frame = Frame(self)
         
         # load grid
         trRegLabel = label(frame, 0, 0, _("Registry:"))
         trReg = self.tester.trRegs[-1] # default is latest
         self.trRegName = gridCombobox(frame, 1, 0, 
                                       value=trReg,
                                       values=self.tester.trRegs, 
                                       comboboxselected=self.dialogTrRegComboBoxSelected)
         trRegToolTipMessage = _("Select Transformation Registry")
         ToolTip(self.trRegName, text=trRegToolTipMessage, wraplength=360)
         ToolTip(trRegLabel, text=trRegToolTipMessage, wraplength=360)
         
         trNameLabel = label(frame, 0, 1, _("Transform:"))
         self.trNameName = gridCombobox(frame, 1, 1, 
                                       value="",
                                       values=self.tester.getTrNames(trReg), 
                                       comboboxselected=self.dialogTrNameComboBoxSelected)
         trRegToolTipMessage = _("Select or enter transform")
         ToolTip(self.trRegName, text=trRegToolTipMessage, wraplength=360)
         ToolTip(trRegLabel, text=trRegToolTipMessage, wraplength=360)
 
         sourceLabel = label(frame, 0, 2, _("Source text:"))
         ToolTip(sourceLabel, text=_("Enter the source text which is to be transformed. "), wraplength=240)
         self.sourceVar = StringVar()
         self.sourceVar.set("")
         sourceEntry = Entry(frame, textvariable=self.sourceVar, width=50)
         sourceLabel.grid(row=2, column=0, sticky=W)
         sourceEntry.grid(row=2, column=1, sticky=EW, pady=3, padx=3)
 
         resultLabel = label(frame, 1, 3, _("Result:"))
         ToolTip(sourceLabel, text=_("Transformation result. "), wraplength=240)
         self.resultVar = StringVar()
         self.resultVar.set("")
         resultEntry = Entry(frame, textvariable=self.resultVar, width=50)
         resultLabel.grid(row=3, column=0, sticky=W)
         resultEntry.grid(row=3, column=1, sticky=EW, pady=3, padx=3)
 
         
         self.mainWin.showStatus(None)
 
         btnPad = 2 if self.mainWin.isMSW else 0 # buttons too narrow on windows
         okButton = Button(frame, text=_("Transform"), width=8 + btnPad, command=self.dialogOk)
         cancelButton = Button(frame, text=_("Done"), width=4 + btnPad, command=self.dialogClose)
         cancelButton.grid(row=4, column=0, sticky=E, columnspan=2, pady=3, padx=3)
         okButton.grid(row=4, column=0, sticky=E, columnspan=2, pady=3, padx=64)
         ToolTip(okButton, text=_("Transform the source entered. "), wraplength=240)
         ToolTip(cancelButton, text=_("Close this dialog. "), wraplength=240)
         
         frame.grid(row=0, column=0, sticky=(N,S,E,W))
         frame.columnconfigure(1, weight=3)
         frame.columnconfigure(2, weight=1)
         window = self.winfo_toplevel()
         window.columnconfigure(0, weight=1)
         self.geometry("+{0}+{1}".format(dialogX+150,dialogY+100))
         
         #self.bind("<Return>", self.ok)
         #self.bind("<Escape>", self.close)
         
         self.protocol("WM_DELETE_WINDOW", self.dialogClose)
         self.grab_set()
         
         self.wait_window(self)
Beispiel #29
0
    def __init__(self, mainWin):
        self.mainWin = mainWin
        parent = mainWin
        super(DialogNewFileOptions, self).__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        
        self.ebaTaxonomyVersion = EBA_TAXONOMY_DEFAULT_VERSION
        self.ebaReportingType = EBA_REPORTING_TYPE_DEFAULT
        self.setEntryPoints()
        self.ebaEntryPointKey = self.ebaEntryPointValues[0]
        self.options = EbaNewFileOptions(self.ebaTaxonomyVersion, self.ebaReportingType,
                                         self.ebaEntryPointValues[0])
        
        options = self.options

        self.transient(self.parent)
        self.title(_("New EBA File"))
        
        frame = Frame(self)
        frame.focus_set()
        
        label(frame, 1, 1, _("Taxonomy version:"))
        self.cellTaxonomyVersion = gridCombobox(frame, 2, 1, getattr(options,"ebaTaxonomyVersion", ""),
                                           values=EBA_TAXONOMY_VERSIONS_VALUES,
                                           comboboxselected = self.onTaxonomyVersionChanged,
                                           width=40)
        ToolTip(self.cellTaxonomyVersion, text=_("Select a taxonomy version"), wraplength=240)

        label(frame, 1, 2, _("EBA reporting type:"))
        self.cellReportType = gridCombobox(frame, 2, 2, getattr(options,"ebaReportingType", ""),
                                           values=EBA_REPORTING_TYPES_VALUES,
                                           comboboxselected = self.onReportTypeChanged,
                                           width=40)
        ToolTip(self.cellReportType, text=_("Select a report type"), wraplength=240)
        label(frame, 1, 3, _("Entry point:"))
        self.cellEntryPoint = gridCombobox(frame, 2, 3, getattr(options,"ebaEntryPointKey", ""),
                                           values=self.ebaEntryPointValues,
                                           comboboxselected = self.onEntryPointChanged,
                                           width=40)
        ToolTip(self.cellEntryPoint, text=_("Select an EBA entry point"), wraplength=240)
        currentRow = 4
        
        self.setEntryPointsCombo()


        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation"))
        okButton = Button(frame, text=_("New"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Create a new file"))
        cancelButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #30
0
    def __init__(self, mainWin, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        parent = mainWin.parent
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                if len(metadataFiles) > 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                metadataFile = metadataFiles[0]
                metadata = filesource.file(filesource.url + os.sep + metadataFile)[0]
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += os.sep
        
                self.nameToUrls, self.remappings = parseTxmyPkg(mainWin, metadata)
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                mainWin.addToLog(err)
                return
    
        mainWin.showStatus(None)
        
        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #31
0
class DialogOpenArchive(Toplevel):
    def __init__(self, parent, openType, filesource, filenames, title, colHeader, showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent # parent is cntlrWinMain
        else: # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        
        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0, column=0, columnspan=4, sticky=(N, S, E, W), padx=3, pady=3)
        self.treeView.focus_set()
        
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                            os.path.splitext(os.path.basename(filesource.url))[0])

        
                self.taxonomyPackage = parsePackage(cntlr, filesource, metadata,
                                                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)
                
                
                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html"):
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(".xhtml"):
                                _type = "Inline Instance"
                                self.packageContainedInstances.append([potentialInstance, _type])
                                packageContentTypeCounts[potentialInstance] = packageContentTypeCounts.get(potentialInstance, 0) + 1
                        if self.packageContainedInstances:
                            break 
                    if self.packageContainedInstances: # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][0] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][0] = "{} {}".format(_type, _dupNo)
                                    
                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _("Failed to parse metadata; the underlying error was: {0}").format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return
    
        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)
        
        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S,E,W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S,E,W), pady=3, padx=3)
        
        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y, column=0, sticky=(S,W), pady=3, padx=3)
        
        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=640, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        
        self.wait_window(self)

    
        
        
    def loadTreeView(self, openType, title, colHeader):
        self.title(title)
        self.openType = openType
        selectedNode = None

        # clear previous treeview entries
        for previousNode in self.treeView.get_children(""): 
            self.treeView.delete(previousNode)

        # set up treeView widget and tabbed pane
        if openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            if openType in (PLUGIN, PACKAGE): width = 770
            else: width = 500
            self.treeView.column("#0", width=width, anchor="w")
            self.treeView.heading("#0", text=colHeader)
            self.isRss = getattr(self.filesource, "isRss", False)
            if self.isRss:
                self.treeView.column("#0", width=350, anchor="w")
                self.treeView["columns"] = ("descr", "date", "instDoc")
                self.treeView.column("descr", width=50, anchor="center", stretch=False)
                self.treeView.heading("descr", text="Form")
                self.treeView.column("date", width=170, anchor="w", stretch=False)
                self.treeView.heading("date", text="Pub Date")
                self.treeView.column("instDoc", width=200, anchor="w", stretch=False)
                self.treeView.heading("instDoc", text="Instance Document")
            elif openType == PLUGIN:
                self.treeView.column("#0", width=150, anchor="w")
                self.treeView["columns"] = ("name", "vers", "descr", "license")
                self.treeView.column("name", width=150, anchor="w", stretch=False)
                self.treeView.heading("name", text="Name")
                self.treeView.column("vers", width=60, anchor="w", stretch=False)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr", width=300, anchor="w", stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license", width=60, anchor="w", stretch=False)
                self.treeView.heading("license", text="License")
            elif openType == PACKAGE:
                self.treeView.column("#0", width=200, anchor="w")
                self.treeView["columns"] = ("vers", "descr", "license")
                self.treeView.column("vers", width=100, anchor="w", stretch=False)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr", width=400, anchor="w", stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license", width=70, anchor="w", stretch=False)
                self.treeView.heading("license", text="License")
            else:
                self.treeView["columns"] = tuple()
        
            loadedPaths = []
            for i, filename in enumerate(self.filenames):
                if isinstance(filename,tuple):
                    if self.isRss:
                        form, date, instDoc = filename[2:5]
                    elif openType == PLUGIN:
                        name, vers, descr, license = filename[3:7]
                    elif openType == PACKAGE:
                        vers, descr, license = filename[3:6]
                    filename = filename[0] # ignore tooltip
                    self.hasToolTip = True
                if filename.endswith("/"):
                    filename = filename[:-1]
                path = filename.split("/")
                if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                    parent = "file{0}".format(loadedPaths.index(path[:-1]))
                else:
                    parent = "" 
                node = self.treeView.insert(parent, "end", "file{0}".format(i), text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc", os.path.basename(instDoc))
                elif openType == PLUGIN:
                    self.treeView.set(node, "name", name)
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                elif openType == PACKAGE:
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=200, anchor="w")
            self.treeView.heading("#0", text="Name")
    
            self.treeView["columns"] = ("url",)
            self.treeView.column("url", width=300, anchor="w")
            self.treeView.heading("url", text="URL")
            
            for fileType, fileUrl in getattr(self, "packageContainedInstances", ()):
                self.treeView.insert("", "end", fileUrl, 
                                     values=fileType, 
                                     text=fileUrl or urls[0][2])
            for name, urls in sorted(self.taxonomyPackage["entryPoints"].items(), key=lambda i:i[0][2]):
                self.treeView.insert("", "end", name, 
                                     values="\n".join(url[1] for url in urls), 
                                     text=name or urls[0][2])
                
            self.hasToolTip = True
        else: # unknown openType
            return None
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)

        if self.showAltViewButton:
            self.altViewButton.config(text=_("Show Files") if openType == ENTRY_POINTS else _("Show Entries"))

        
    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            if hasattr(self, "taxonomyPackage"):
                # load file source remappings
                self.filesource.mappedPaths = self.taxonomyPackage["remappings"]
            filename = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                filename = self.filenames[int(selection[0][4:])]
                if isinstance(filename,tuple):
                    if self.isRss:
                        filename = filename[4]
                    else:
                        filename = filename[0]
            elif self.openType == ENTRY_POINTS:
                epName = selection[0]
                #index 0 is the remapped Url, as opposed to the canonical one used for display
                # Greg Acsone reports [0] does not work for Corep 1.6 pkgs, need [1], old style packages
                filenames = []
                for _url, _type in self.packageContainedInstances: # check if selection was an inline instance
                    if _type == epName:
                        filenames.append(_url)
                if not filenames: # else if it's a named taxonomy entry point
                    for url in self.taxonomyPackage["entryPoints"][epName]:
                        filename = url[0]
                        if not filename.endswith("/"):
                            # check if it's an absolute URL rather than a path into the archive
                            if not isHttpUrl(filename) and self.metadataFilePrefix != self.taxonomyPkgMetaInf:
                                # assume it's a path inside the archive:
                                filename = self.metadataFilePrefix + filename
                        filenames.append(filename)
                if filenames:
                    self.filesource.select(filenames)
                    self.accepted = True
                    self.close()
                return
            elif self.openType in (PLUGIN, PACKAGE):
                filename = self.filenames[int(selection[0][4:])][2]
            if filename is not None and not filename.endswith("/"):
                if hasattr(self, "taxonomyPackage"):
                    # attempt to unmap the filename to original file
                    # will be mapped again in loading, but this allows schemaLocation to be unmapped
                    for prefix, remapping in self.taxonomyPackage["remappings"].items():
                        if isHttpUrl(remapping):
                            remapStart = remapping
                        else:
                            remapStart = self.metadataFilePrefix + remapping
                        if filename.startswith(remapStart):
                            # set unmmapped file
                            filename = prefix + filename[len(remapStart):]
                            break
                if self.openType in (PLUGIN, PACKAGE):
                    self.filesource.selection = filename
                else:
                    self.filesource.select(filename)
                self.accepted = True
                self.close()
                        
        
    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()
        
    def showAltView(self, event=None):
        if self.openType == ENTRY_POINTS:
            self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File"))
        else:
            self.loadTreeView(ENTRY_POINTS, _("Select Archive File"), _("File"))
        
    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvRowId != self.toolTipRowId:
            text = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
                self.toolTipRowId = tvRowId
                if tvRowId and len(tvRowId) > 4:
                    try:
                        text = self.filenames[ int(tvRowId[4:]) ]
                        if isinstance(text, tuple):
                            text = (text[1] or "").replace("\\n","\n")
                    except (KeyError, ValueError):
                        pass
            elif self.openType == ENTRY_POINTS:
                try:
                    text = "{0}\n{1}".format(tvRowId, 
                             "\n".join(url[1] for url in self.taxonomyPackage["entryPoints"][tvRowId]))
                except KeyError:
                    pass
            self.setToolTip(text)
                
    def setToolTip(self, text):
        self.toolTip._hide()
        if text:
            self.toolTipText.set(text)
            self.toolTip.configure(state="normal")
            self.toolTip._schedule()
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")
Beispiel #32
0
class ViewList():
    def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False):
        self.tabWin = tabWin
        self.viewFrame = Frame(tabWin)
        self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        tabWin.add(self.viewFrame,text=tabTitle)
        xmlScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
        self.listBox = Listbox(self.viewFrame, yscrollcommand=xmlScrollbar.set)
        self.listBox.grid(row=0, column=0, sticky=(N, S, E, W))
        #self.listBox.focus_set()
        self.listBox.bind("<Motion>", self.listBoxMotion, '+')
        self.listBox.bind("<Leave>", self.listBoxLeave, '+')
        xmlScrollbar["command"] = self.listBox.yview
        xmlScrollbar.grid(row=0, column=1, sticky=(N,S))
        self.viewFrame.columnconfigure(0, weight=1)
        self.viewFrame.rowconfigure(0, weight=1)
        self.listBoxToolTipText = StringVar()
        if hasToolTip:
            self.listBoxToolTip = ToolTip(self.listBox, textvariable=self.listBoxToolTipText, wraplength=480, follow_mouse=True, state="disabled")
            self.listBoxRow = -9999999
        self.modelXbrl = modelXbrl
        if modelXbrl:
            modelXbrl.views.append(self)
    
    def close(self):
        self.tabWin.forget(self.viewFrame)
        self.modelXbrl.views.remove(self)
        self.modelXbrl = None
        
    def select(self):
        self.tabWin.select(self.viewFrame)
        
    def append(self, line):
        self.listBox.insert(END, line)

    def clear(self):
        self.listBox.delete(0,END)
        
    def listBoxLeave(self, *args):
        self.listBoxRow = -9999999
        
    def lines(self):
        return self.listBox.get(0,END)

    def lineText(self, lineNumber):
        return self.listBox.get(lineNumber)
    
    def selectLine(self, lineNumber):
        self.listBox.selection_clear(0,END)
        self.listBox.selection_set(lineNumber)

    def saveToFile(self, filename):
        with open(filename, "w") as fh:
            fh.writelines([logEntry + '\n' for logEntry in self.listBox.get(0,END)])
            
    def copyToClipboard(self, cntlr=None, *ignore):
        if cntlr is None: cntlr = self.modelXbrl.modelManager.cntlr
        cntlr.clipboardData(text='\n'.join(self.listBox.get(0,END)))
            
    def listBoxMotion(self, *args):
        lbRow = self.listBox.nearest(args[0].y)
        if lbRow != self.listBoxRow:
            self.listBoxRow = lbRow
            text = self.listBox.get(lbRow)
            self.listBoxToolTip._hide()
            if text and len(text) > 0:
                if len(text) * 8 > 200:
                    self.listBoxToolTipText.set(text)
                    self.listBoxToolTip.configure(state="normal")
                    self.listBoxToolTip._schedule()
                else:
                    self.listBoxToolTipText.set("")
                    self.listBoxToolTip.configure(state="disabled")
            else:
                self.listBoxToolTipText.set("")
                self.listBoxToolTip.configure(state="disabled")
    
    def contextMenu(self,contextMenuClick=None):
        try:
            return self.menu
        except AttributeError:
            if contextMenuClick is None: contextMenuClick = self.modelXbrl.modelManager.cntlr.contextMenuClick
            self.menu = Menu( self.viewFrame, tearoff = 0 )
            self.listBox.bind( contextMenuClick, self.popUpMenu )
            return self.menu
    
    def popUpMenu(self, event):
        self.menu.post( event.x_root, event.y_root )

    def menuAddSaveClipboard(self):
        self.menu.add_command(label=_("Save to file"), underline=0, command=self.modelXbrl.modelManager.cntlr.fileSave)
        if self.modelXbrl.modelManager.cntlr.hasClipboard:
            self.menu.add_command(label=_("Copy to clipboard"), underline=0, command=self.copyToClipboard)
Beispiel #33
0
class ViewTree:
    def __init__(self,
                 modelXbrl,
                 tabWin,
                 tabTitle,
                 hasToolTip=False,
                 lang=None):
        self.tabWin = tabWin
        self.viewFrame = Frame(tabWin)
        self.viewFrame.view = self
        self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        tabWin.add(self.viewFrame, text=tabTitle)
        self.tabTitle = tabTitle  # for error messages
        vScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(self.viewFrame, orient=HORIZONTAL)
        self.treeView = Treeview(self.viewFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.treeView.tag_configure("ELR", background="#E0F0FF")
        self.treeView.tag_configure("even", background="#F0F0F0")
        self.treeView.tag_configure("odd", background="#FFFFFF")
        if modelXbrl.modelManager.cntlr.isMac or modelXbrl.modelManager.cntlr.isMSW:
            highlightColor = "#%04x%04x%04x" % self.treeView.winfo_rgb(
                "SystemHighlight")
        else:
            highlightColor = "#33339999ffff"  # using MSW value for Unix/Linux which has no named colors
        self.treeView.tag_configure("selected-ELR", background=highlightColor)
        self.treeView.tag_configure("selected-even", background=highlightColor)
        self.treeView.tag_configure("selected-odd", background=highlightColor)
        self.treeViewSelection = ()
        self.treeView.bind("<<TreeviewSelect>>", self.viewSelectionChange, '+')
        self.treeView.bind("<1>", self.onViewClick, '+')
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        self.viewFrame.columnconfigure(0, weight=1)
        self.viewFrame.rowconfigure(0, weight=1)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=480,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        self.lang = lang
        self.labelrole = None
        self.nameIsPrefixed = False
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang:
                self.lang = modelXbrl.modelManager.defaultLang

    def clearTreeView(self):
        self.treeViewSelection = ()
        for node in self.treeView.get_children():
            self.treeView.delete(node)

    def viewSelectionChange(self, event=None):
        for node in self.treeViewSelection:
            if self.treeView.exists(node):
                priorTags = self.treeView.item(node)["tags"]
                if priorTags:
                    priorBgTag = priorTags[0]
                    if priorBgTag.startswith("selected-"):
                        self.treeView.item(node, tags=(priorBgTag[9:], ))
        self.treeViewSelection = self.treeView.selection()
        for node in self.treeViewSelection:
            priorTags = self.treeView.item(node)["tags"]
            if priorTags:
                self.treeView.item(node, tags=("selected-" + priorTags[0], ))

    def onViewClick(self, *args):
        self.modelXbrl.modelManager.cntlr.currentView = self

    def close(self):
        del self.viewFrame.view
        if self.modelXbrl:
            self.tabWin.forget(self.viewFrame)
            self.modelXbrl.views.remove(self)
            self.modelXbrl = None
            self.view = None

    def select(self):
        self.tabWin.select(self.viewFrame)

    def leave(self, *args):
        self.toolTipColId = None
        self.toolTipRowId = None

    def motion(self, *args):
        tvColId = self.treeView.identify_column(args[0].x)
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvColId != self.toolTipColId or tvRowId != self.toolTipRowId:
            self.toolTipColId = tvColId
            self.toolTipRowId = tvRowId
            newValue = self.getToolTip(tvRowId, tvColId)
            if newValue is None and tvRowId and len(tvRowId) > 0:
                try:
                    col = int(tvColId[1:])
                    if col == 0:
                        newValue = self.treeView.item(tvRowId, "text")
                    else:
                        values = self.treeView.item(tvRowId, "values")
                        if col <= len(values):
                            newValue = values[col - 1]
                except ValueError:
                    pass
            self.setToolTip(newValue, tvColId)

    def getToolTip(self, rowId, colId):
        return None

    def setToolTip(self, text, colId="#0"):
        self.toolTip._hide()
        if isinstance(text, str) and len(text) > 0:
            width = self.treeView.column(colId, "width")
            if len(text) * 8 > width or '\n' in text:
                self.toolTipText.set(text)
                self.toolTip.configure(state="normal")
                self.toolTip._schedule()
            else:
                self.toolTipText.set("")
                self.toolTip.configure(state="disabled")
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")

    def contextMenu(self):
        try:
            return self.menu
        except AttributeError:
            try:
                self.menu = Menu(self.viewFrame, tearoff=0)
                self.treeView.bind(
                    self.modelXbrl.modelManager.cntlr.contextMenuClick,
                    self.popUpMenu, '+')
                return self.menu
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating context menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None
                return None

    def popUpMenu(self, event):
        if self.menu:
            self.menuRow = self.treeView.identify_row(event.y)
            self.menuCol = self.treeView.identify_column(event.x)
            self.menu.post(event.x_root, event.y_root)

    def expand(self):
        self.setTreeItemOpen(self.menuRow, open=True)

    def expandAll(self):
        self.setTreeItemOpen("", open=True)

    def collapse(self):
        self.setTreeItemOpen(self.menuRow, open=False)

    def collapseAll(self):
        self.setTreeItemOpen("", open=False)

    def setTreeItemOpen(self, node, open=True):
        if node:
            self.treeView.item(node, open=open)
        for childNode in self.treeView.get_children(node):
            self.setTreeItemOpen(childNode, open)

    def menuAddExpandCollapse(self):
        if self.menu:
            self.menu.add_command(label=_("Expand"),
                                  underline=0,
                                  command=self.expand)
            self.menu.add_command(label=_("Collapse"),
                                  underline=0,
                                  command=self.collapse)
            self.menu.add_command(label=_("Expand all"),
                                  underline=0,
                                  command=self.expandAll)
            self.menu.add_command(label=_("Collapse all"),
                                  underline=0,
                                  command=self.collapseAll)

    def menuAddClipboard(self):
        if self.menu and self.modelXbrl.modelManager.cntlr.hasClipboard:
            try:
                clipboardMenu = Menu(self.viewFrame, tearoff=0)
                clipboardMenu.add_command(label=_("Cell"),
                                          underline=0,
                                          command=self.copyCellToClipboard)
                clipboardMenu.add_command(label=_("Row"),
                                          underline=0,
                                          command=self.copyRowToClipboard)
                clipboardMenu.add_command(label=_("Table"),
                                          underline=0,
                                          command=self.copyTableToClipboard)
                self.menu.add_cascade(label=_("Copy to clipboard"),
                                      menu=clipboardMenu,
                                      underline=0)
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating clipboard menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None

    def menuAddLangs(self):
        if self.menu:
            try:
                langsMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=_("Language"),
                                      menu=langsMenu,
                                      underline=0)
                for lang in sorted(self.modelXbrl.langs):
                    langsMenu.add_command(
                        label=lang,
                        underline=0,
                        command=lambda l=lang: self.setLang(l))
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating context languages menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None

    def menuAddLabelRoles(self, includeConceptName=False, menulabel=None):
        if self.menu:
            try:
                if menulabel is None: menulabel = _("Label role")
                rolesMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=menulabel,
                                      menu=rolesMenu,
                                      underline=0)
                from arelle.ModelRelationshipSet import labelroles
                for x in labelroles(self.modelXbrl, includeConceptName):
                    rolesMenu.add_command(
                        label=x[0][1:],
                        underline=0,
                        command=lambda a=x[1]: self.setLabelrole(a))
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating context label roles menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None

    def menuAddNameStyle(self, menulabel=None):
        if self.menu:
            try:
                if menulabel is None: menulabel = _("Name Style")
                nameStyleMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=menulabel,
                                      menu=nameStyleMenu,
                                      underline=0)
                from arelle.ModelRelationshipSet import labelroles
                nameStyleMenu.add_command(
                    label=_("Prefixed"),
                    underline=0,
                    command=lambda a=True: self.setNamestyle(a))
                nameStyleMenu.add_command(
                    label=_("No prefix"),
                    underline=0,
                    command=lambda a=False: self.setNamestyle(a))
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating context name style menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None

    def menuAddUnitDisplay(self):
        if self.menu:
            try:
                rolesMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=_("Units"),
                                      menu=rolesMenu,
                                      underline=0)
                rolesMenu.add_command(
                    label=_("Unit ID"),
                    underline=0,
                    command=lambda: self.setUnitDisplay(unitDisplayID=True))
                rolesMenu.add_command(
                    label=_("Measures"),
                    underline=0,
                    command=lambda: self.setUnitDisplay(unitDisplayID=False))
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating context unit menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None

    def menuAddViews(self, addClose=True, tabWin=None):
        if self.menu:
            try:
                if tabWin is None: tabWin = self.tabWin
                viewMenu = Menu(self.viewFrame, tearoff=0)
                self.menu.add_cascade(label=_("View"),
                                      menu=viewMenu,
                                      underline=0)
                newViewsMenu = Menu(self.viewFrame, tearoff=0)
                if addClose:
                    viewMenu.add_command(label=_("Close"),
                                         underline=0,
                                         command=self.close)
                viewMenu.add_cascade(label=_("Additional view"),
                                     menu=newViewsMenu,
                                     underline=0)
                newViewsMenu.add_command(
                    label=_("Arcrole group..."),
                    underline=0,
                    command=lambda: self.newArcroleGroupView(tabWin))
                from arelle.ModelRelationshipSet import baseSetArcroles
                for x in baseSetArcroles(self.modelXbrl) + [
                    (" Role Types", "!CustomRoleTypes!"),
                    (" Arcrole Types", "!CustomArcroleTypes!")
                ]:
                    newViewsMenu.add_command(
                        label=x[0][1:],
                        underline=0,
                        command=lambda a=x[1]: self.newView(a, tabWin))
            except Exception as ex:  # tkinter menu problem maybe
                self.modelXbrl.info(
                    "arelle:internalException",
                    _("Exception creating context add-views menu in %(title)s: %(error)s"
                      ),
                    modelObject=self.modelXbrl.modelDocument,
                    title=self.tabTitle,
                    error=str(ex))
                self.menu = None

    def newView(self, arcrole, tabWin):
        if arcrole in ("!CustomRoleTypes!", "!CustomArcroleTypes!"):
            from arelle import ViewWinRoleTypes
            ViewWinRoleTypes.viewRoleTypes(self.modelXbrl,
                                           tabWin,
                                           arcrole == "!CustomArcroleTypes!",
                                           lang=self.lang)
        else:
            from arelle import ViewWinRelationshipSet
            ViewWinRelationshipSet.viewRelationshipSet(self.modelXbrl,
                                                       tabWin,
                                                       arcrole,
                                                       lang=self.lang)

    def newArcroleGroupView(self, tabWin):
        from arelle.DialogArcroleGroup import getArcroleGroup
        from arelle import ViewWinRelationshipSet
        arcroleGroup = getArcroleGroup(self.modelXbrl.modelManager.cntlr,
                                       self.modelXbrl)
        if arcroleGroup:
            ViewWinRelationshipSet.viewRelationshipSet(self.modelXbrl,
                                                       tabWin,
                                                       arcroleGroup,
                                                       lang=self.lang)

    def setLang(self, lang):
        self.lang = lang
        self.view()

    def setLabelrole(self, labelrole):
        self.labelrole = labelrole
        self.view()

    def setNamestyle(self, isPrefixed):
        self.nameIsPrefixed = isPrefixed
        self.view()

    def setUnitDisplay(self, unitDisplayID=False):
        self.unitDisplayID = unitDisplayID
        self.view()

    def setColumnsSortable(self,
                           treeColIsInt=False,
                           startUnsorted=False,
                           initialSortCol="#0",
                           initialSortDirForward=True):
        if hasattr(self, 'lastSortColumn') and self.lastSortColumn:
            self.treeView.heading(self.lastSortColumn,
                                  image=self.sortImages[2])
        self.lastSortColumn = None if startUnsorted else initialSortCol
        self.lastSortColumnForward = initialSortDirForward
        self.treeColIsInt = treeColIsInt
        if not hasattr(self, "sortImages"):
            self.sortImages = (PhotoImage(
                file=os.path.join(self.modelXbrl.modelManager.cntlr.imagesDir,
                                  "columnSortUp.gif")),
                               PhotoImage(file=os.path.join(
                                   self.modelXbrl.modelManager.cntlr.imagesDir,
                                   "columnSortDown.gif")), PhotoImage())
        for col in ("#0", ) + self.treeView["columns"]:
            self.treeView.heading(col,
                                  command=lambda c=col: self.sortColumn(c))
        if not startUnsorted:
            self.treeView.heading(
                initialSortCol,
                image=self.sortImages[not initialSortDirForward])

    def colSortVal(self, node, col):
        if col == "#0":
            treeColVal = self.treeView.item(node)["text"]
            if self.treeColIsInt:
                return int(treeColVal)
        else:
            treeColVal = self.treeView.set(node, col)
            if col == "sequence":
                try:
                    return int(treeColVal)
                except:
                    return 0
        return treeColVal

    def sortNestedRows(self, parentNode, col, reverse):
        l = [(self.colSortVal(node, col), node)
             for node in self.treeView.get_children(parentNode)]
        l.sort(reverse=reverse)
        # rearrange items in sorted positions
        for i, (cell, node) in enumerate(l):
            self.treeView.move(node, parentNode, i)
        # reset even/odd tags
        for i, node in enumerate(self.treeView.get_children(parentNode)):
            self.treeView.item(node, tags=('even' if i & 1 else 'odd', ))
            self.sortNestedRows(node, col, reverse)

    def sortColumn(self, col):
        if col == self.lastSortColumn:
            reverse = self.lastSortColumnForward
            self.lastSortColumnForward = not reverse
        else:
            if self.lastSortColumn:
                self.treeView.heading(self.lastSortColumn,
                                      image=self.sortImages[2])
            reverse = False
            self.lastSortColumnForward = True
            self.lastSortColumn = col
        self.treeView.heading(col, image=self.sortImages[reverse])
        self.sortNestedRows('', col, reverse)
        self.viewSelectionChange()  # reselect selected rows

    def copyCellToClipboard(self, *ignore):
        self.modelXbrl.modelManager.cntlr.clipboardData(
            text=self.treeView.item(self.menuRow)['text'] if self.menuCol ==
            '#0' else self.treeView.set(self.menuRow, self.menuCol))

    def copyRowToClipboard(self, *ignore):
        self.modelXbrl.modelManager.cntlr.clipboardData(
            text='\t'.join([self.treeView.item(self.menuRow)['text']] + [
                self.treeView.set(self.menuRow, c)
                for c in self.treeView['columns']
            ]))

    def copyTableToClipboard(self, *ignore):
        cols = self.treeView['columns']
        lines = [
            '\t'.join([self.treeView.heading('#0')['text']] +
                      [self.treeView.heading(h)['text'] for h in cols])
        ]
        self.tabLines('', '', cols, lines)
        self.modelXbrl.modelManager.cntlr.clipboardData(text='\n'.join(lines))

    def tabLines(self, parentNode, indent, cols, lines):
        for node in self.treeView.get_children(parentNode):
            lines.append('\t'.join(
                '"{}"'.format(c.replace('"', '""')) if (
                    isinstance(c, str) and "\n" in c) else c
                for c in ([indent + self.treeView.item(node)['text']] +
                          [self.treeView.set(node, c) for c in cols])))
            self.tabLines(node, indent + '    ', cols, lines)
class DialogOpenArchive(Toplevel):
    def __init__(self,
                 parent,
                 openType,
                 filesource,
                 filenames,
                 title,
                 colHeader,
                 showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent  # parent is cntlrWinMain
        else:  # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(
                    os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                    os.path.splitext(os.path.basename(filesource.url))[0])

                self.taxonomyPackage = parsePackage(
                    cntlr, filesource, metadata,
                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)

                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html"):
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(".xhtml"):
                                _type = "Inline Instance"
                                self.packageContainedInstances.append(
                                    [potentialInstance, _type])
                                packageContentTypeCounts[
                                    potentialInstance] = packageContentTypeCounts.get(
                                        potentialInstance, 0) + 1
                        if self.packageContainedInstances:
                            break
                    if self.packageContainedInstances:  # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(
                                        len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][
                                            0] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][
                                            0] = "{} {}".format(_type, _dupNo)

                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _(
                    "Failed to parse metadata; the underlying error was: {0}"
                ).format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)

        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y,
                                    column=0,
                                    sticky=(S, W),
                                    pady=3,
                                    padx=3)

        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))
        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()

        self.wait_window(self)

    def loadTreeView(self, openType, title, colHeader):
        self.title(title)
        self.openType = openType
        selectedNode = None

        # clear previous treeview entries
        for previousNode in self.treeView.get_children(""):
            self.treeView.delete(previousNode)

        # set up treeView widget and tabbed pane
        if openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            if openType in (PLUGIN, PACKAGE): width = 770
            else: width = 500
            self.treeView.column("#0", width=width, anchor="w")
            self.treeView.heading("#0", text=colHeader)
            self.isRss = getattr(self.filesource, "isRss", False)
            if self.isRss:
                self.treeView.column("#0", width=350, anchor="w")
                self.treeView["columns"] = ("descr", "date", "instDoc")
                self.treeView.column("descr",
                                     width=50,
                                     anchor="center",
                                     stretch=False)
                self.treeView.heading("descr", text="Form")
                self.treeView.column("date",
                                     width=170,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("date", text="Pub Date")
                self.treeView.column("instDoc",
                                     width=200,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("instDoc", text="Instance Document")
            elif openType == PLUGIN:
                self.treeView.column("#0", width=150, anchor="w")
                self.treeView["columns"] = ("name", "vers", "descr", "license")
                self.treeView.column("name",
                                     width=150,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("name", text="Name")
                self.treeView.column("vers",
                                     width=60,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr",
                                     width=300,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license",
                                     width=60,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("license", text="License")
            elif openType == PACKAGE:
                self.treeView.column("#0", width=200, anchor="w")
                self.treeView["columns"] = ("vers", "descr", "license")
                self.treeView.column("vers",
                                     width=100,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("vers", text="Version")
                self.treeView.column("descr",
                                     width=400,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("descr", text="Description")
                self.treeView.column("license",
                                     width=70,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("license", text="License")
            else:
                self.treeView["columns"] = tuple()

            loadedPaths = []
            for i, filename in enumerate(self.filenames):
                if isinstance(filename, tuple):
                    if self.isRss:
                        form, date, instDoc = filename[2:5]
                    elif openType == PLUGIN:
                        name, vers, descr, license = filename[3:7]
                    elif openType == PACKAGE:
                        vers, descr, license = filename[3:6]
                    filename = filename[0]  # ignore tooltip
                    self.hasToolTip = True
                if filename.endswith("/"):
                    filename = filename[:-1]
                path = filename.split("/")
                if not self.isRss and len(
                        path) > 1 and path[:-1] in loadedPaths:
                    parent = "file{0}".format(loadedPaths.index(path[:-1]))
                else:
                    parent = ""
                node = self.treeView.insert(parent,
                                            "end",
                                            "file{0}".format(i),
                                            text=path[-1])
                if self.isRss:
                    self.treeView.set(node, "descr", form)
                    self.treeView.set(node, "date", date)
                    self.treeView.set(node, "instDoc",
                                      os.path.basename(instDoc))
                elif openType == PLUGIN:
                    self.treeView.set(node, "name", name)
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                elif openType == PACKAGE:
                    self.treeView.set(node, "vers", vers)
                    self.treeView.set(node, "descr", descr)
                    self.treeView.set(node, "license", license)
                if self.selection == filename:
                    selectedNode = node
                loadedPaths.append(path)

        elif openType == ENTRY_POINTS:
            self.treeView.column("#0", width=200, anchor="w")
            self.treeView.heading("#0", text="Name")

            self.treeView["columns"] = ("url", )
            self.treeView.column("url", width=300, anchor="w")
            self.treeView.heading("url", text="URL")

            for fileType, fileUrl in getattr(self, "packageContainedInstances",
                                             ()):
                self.treeView.insert("",
                                     "end",
                                     fileUrl,
                                     values=fileType,
                                     text=fileUrl or urls[0][2])
            for name, urls in sorted(
                    self.taxonomyPackage["entryPoints"].items(),
                    key=lambda i: i[0][2]):
                self.treeView.insert("",
                                     "end",
                                     name,
                                     values="\n".join(url[1] for url in urls),
                                     text=name or urls[0][2])

            self.hasToolTip = True
        else:  # unknown openType
            return None
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)

        if self.showAltViewButton:
            self.altViewButton.config(text=_("Show Files") if openType ==
                                      ENTRY_POINTS else _("Show Entries"))

    def ok(self, event=None):
        selection = self.treeView.selection()
        if len(selection) > 0:
            if hasattr(self, "taxonomyPackage"):
                # load file source remappings
                self.filesource.mappedPaths = self.taxonomyPackage[
                    "remappings"]
            filename = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM):
                filename = self.filenames[int(selection[0][4:])]
                if isinstance(filename, tuple):
                    if self.isRss:
                        filename = filename[4]
                    else:
                        filename = filename[0]
            elif self.openType == ENTRY_POINTS:
                epName = selection[0]
                #index 0 is the remapped Url, as opposed to the canonical one used for display
                # Greg Acsone reports [0] does not work for Corep 1.6 pkgs, need [1], old style packages
                filenames = []
                for _url, _type in self.packageContainedInstances:  # check if selection was an inline instance
                    if _type == epName:
                        filenames.append(_url)
                if not filenames:  # else if it's a named taxonomy entry point
                    for url in self.taxonomyPackage["entryPoints"][epName]:
                        filename = url[0]
                        if not filename.endswith("/"):
                            # check if it's an absolute URL rather than a path into the archive
                            if not isHttpUrl(
                                    filename
                            ) and self.metadataFilePrefix != self.taxonomyPkgMetaInf:
                                # assume it's a path inside the archive:
                                filename = self.metadataFilePrefix + filename
                        filenames.append(filename)
                if filenames:
                    self.filesource.select(filenames)
                    self.accepted = True
                    self.close()
                return
            elif self.openType in (PLUGIN, PACKAGE):
                filename = self.filenames[int(selection[0][4:])][2]
            if filename is not None and not filename.endswith("/"):
                if hasattr(self, "taxonomyPackage"):
                    # attempt to unmap the filename to original file
                    # will be mapped again in loading, but this allows schemaLocation to be unmapped
                    for prefix, remapping in self.taxonomyPackage[
                            "remappings"].items():
                        if isHttpUrl(remapping):
                            remapStart = remapping
                        else:
                            remapStart = self.metadataFilePrefix + remapping
                        if filename.startswith(remapStart):
                            # set unmmapped file
                            filename = prefix + filename[len(remapStart):]
                            break
                if self.openType in (PLUGIN, PACKAGE):
                    self.filesource.selection = filename
                else:
                    self.filesource.select(filename)
                self.accepted = True
                self.close()

    def close(self, event=None):
        self.parent.focus_set()
        self.destroy()

    def showAltView(self, event=None):
        if self.openType == ENTRY_POINTS:
            self.loadTreeView(ARCHIVE, _("Select Entry Point"), _("File"))
        else:
            self.loadTreeView(ENTRY_POINTS, _("Select Archive File"),
                              _("File"))

    def leave(self, *args):
        self.toolTipRowId = None

    def motion(self, *args):
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvRowId != self.toolTipRowId:
            text = None
            if self.openType in (ARCHIVE, DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
                self.toolTipRowId = tvRowId
                if tvRowId and len(tvRowId) > 4:
                    try:
                        text = self.filenames[int(tvRowId[4:])]
                        if isinstance(text, tuple):
                            text = (text[1] or "").replace("\\n", "\n")
                    except (KeyError, ValueError):
                        pass
            elif self.openType == ENTRY_POINTS:
                try:
                    text = "{0}\n{1}".format(
                        tvRowId, "\n".join(
                            url[1] for url in
                            self.taxonomyPackage["entryPoints"][tvRowId]))
                except KeyError:
                    pass
            self.setToolTip(text)

    def setToolTip(self, text):
        self.toolTip._hide()
        if text:
            self.toolTipText.set(text)
            self.toolTip.configure(state="normal")
            self.toolTip._schedule()
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")
Beispiel #35
0
    def __init__(self, mainWin, options, reportType, endDate):
        self.reportType = reportType
        self.mainWin = mainWin
        self.endDate = endDate
        parent = mainWin
        super(DialogCssfSaveOptions, self).__init__(parent)
        self.parent = parent
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.accountingVersionValues = ACCOUNTING_VERSION_VALUES
        if reportType == SCOREP_REPORT:
            self.accountingVersionValues = self.accountingVersionValues + ACCOUNTING_SUBSIDIARY

        self.transient(self.parent)
        self.title(_("Save As CSSF Options"))
        
        frame = Frame(self)

        label(frame, 1, 1, _("Entity type:"))
        self.cellEntityType = gridCombobox(frame, 2, 1, getattr(options,"entityType",""), values=COMPANY_TYPE_VALUES)
        ToolTip(self.cellEntityType, text=_("Select an entity type"), wraplength=240)
        label(frame, 1, 2, _("CSSF entity code:"))
        self.cellCssfCode = gridCell(frame, 2, 2, getattr(options,"cssfCode",""))
        ToolTip(self.cellCssfCode, text=_("Enter a CSSF entity code (up to {0} digits)").format(CSSF_CODE_LENGTH), wraplength=240)
        currentRow = 3
        if reportType.endswith(COREP_REPORT_SUFFIX):
            label(frame, 1, currentRow, _("Ratio type:"))
            defaultValue = getattr(options, "ratioType","")
            if defaultValue not in RATIO_TYPE_VALUES:
                defaultValue = RATIO_TYPE_VALUES[0]
            self.cellRatioType = gridCombobox(frame, 2, currentRow, defaultValue, values=RATIO_TYPE_VALUES)
            ToolTip(self.cellRatioType, text=_("Select how the ratios are computed"), wraplength=240)
            currentRow += 1
        if reportType[0] != CONSOLIDATED_REPORT_PREFIX:
            label(frame, 1, currentRow, _("Accounting version:"))
            defaultValue = getattr(options, "accountingVersion", "")
            if defaultValue not in self.accountingVersionValues:
                defaultValue = ACCOUNTING_VERSION_DEFAULT
            self.cellAccountingVersion = gridCombobox(frame, 2, currentRow, defaultValue, values=self.accountingVersionValues)
            ToolTip(self.cellAccountingVersion, text=_("Select the accounting version"), wraplength=240)
            currentRow += 1
        if reportType == FINREP_REPORT:
            label(frame, 1, currentRow, _("Figures type:"))
            self.cellFiguresType = gridCombobox(frame, 2, currentRow, getattr(options,"figuresType",""), values=FIGURES_TYPE_VALUES)
            ToolTip(self.cellFiguresType, text=_("Select a figures type"), wraplength=240)
            currentRow += 1

        cancelButton = Button(frame, text=_("Cancel"), width=8, command=self.close)
        ToolTip(cancelButton, text=_("Cancel operation, discarding changes and entries"))
        okButton = Button(frame, text=_("OK"), width=8, command=self.ok)
        ToolTip(okButton, text=_("Accept the options as entered above"))
        cancelButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=3)
        okButton.grid(row=currentRow, column=1, columnspan=3, sticky=E, pady=3, padx=86)
        
        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #36
0
    def __init__(self, mainWin, options):
        parent = mainWin.parent
        super(DialogFind, self).__init__(parent)
        self.parent = parent
        self.modelManager = mainWin.modelManager
        self.modelXbrl = None  # set when Find pressed, this blocks next prematurely
        if options is None: options = newFindOptions
        self.options = options
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogW = int(parentGeometry.group(1))
        dialogH = int(parentGeometry.group(2))
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(_("Find"))

        self.objsList = []  # next may be tried before anything is found

        frame = Frame(self)

        # load grid
        findLabel = gridHdr(frame, 1, 0, "Find:", anchor="w")
        findLabel.grid(padx=8)
        self.cbExpr = gridCombobox(frame,
                                   1,
                                   1,
                                   values=options["priorExpressions"])
        self.cbExpr.grid(columnspan=3, padx=8)
        ToolTip(
            self.cbExpr,
            text=
            _("Enter expression to find, or select from combo box drop down history list."
              ),
            wraplength=240)

        y = 2

        # checkbox entries
        label(frame, 1, y, "Direction:")
        label(frame, 1, y + 3, "Match:")
        scopeLabel = label(frame, 2, y, "Scope:")
        ToolTip(scopeLabel,
                text=_("Scope for an XBRL document (instance or DTS).  "
                       "For an RSS Feed, all properties are matched.  "),
                wraplength=240)
        rbUp = radiobutton(frame, 1, y + 1, "Up", "up", "direction")
        ToolTip(rbUp,
                text=_("Find/Next up (on screen) from last to first match."),
                wraplength=240)
        rbDn = radiobutton(frame, 1, y + 2, "Down", "down", "direction",
                           rbUp.valueVar)
        ToolTip(rbDn,
                text=_("Find/Next down (on screen) from first to last match."),
                wraplength=240)
        rbText = radiobutton(frame, 1, y + 4, "Text (ignore case)", "text",
                             "exprType")
        ToolTip(
            rbText,
            text=_(
                "Expression is a set of characters to match, ignoring case.  "
                "The match may occur anywhere within the scope. "),
            wraplength=360)
        rbRegex = radiobutton(frame, 1, y + 5, "Regular expression", "regex",
                              "exprType", rbText.valueVar)
        ToolTip(
            rbRegex,
            text=
            _('A regular expression to match, anywhere in the scope, ignoring case.  '
              'For example, "cash" would match cash anywhere in a string (like cash on hand), '
              'whereas "^cash$" would match a full string to only contain cash. '
              'Use regular expression metacharacters, e.g., "." for any single character, '
              '".*" for any number of wild characters, .{3} for exactly 3 wild characters. '
              ),
            wraplength=360)
        rbXPath = radiobutton(frame, 1, y + 6, "XPath 2 expression", "xpath",
                              "exprType", rbText.valueVar)
        ToolTip(
            rbXPath,
            text=
            _('An XPath 2 expression, where the context element, ".", is a candidate concept QName, if any concept scope is checked, '
              'and a candidate fact item, if any fact scope is checked.  The XPath 2 functions do not need an "fn:" prefix (but it is defined).  '
              'The XBRL Functions Registry functions do require an "xfi:" prefix.  Constructors require an "xs:" prefix.  '
              'The expression is considered "matched" for the candidate concept QNames or fact items where the effective boolean value of the expression is "true()".  '
              ),
            wraplength=360)
        self.optionControls = (
            rbUp,
            rbDn,
            rbText,
            rbRegex,
            rbXPath,
            #checkbox(frame, 2, y + 1, "All", "all"),
            checkbox(frame, 2, y + 1, "Concept label", "conceptLabel"),
            checkbox(frame, 2, y + 2, "   name", "conceptName"),
            checkbox(frame, 2, y + 3, "   type", "conceptType"),
            checkbox(frame, 2, y + 4, "   subs group", "conceptSubs"),
            checkbox(frame, 2, y + 5, "   period type", "conceptPer"),
            checkbox(frame, 2, y + 6, "   balance", "conceptBal"),
            checkbox(frame, 3, y + 1, "Fact label", "factLabel"),
            checkbox(frame, 3, y + 2, "   name", "factName"),
            checkbox(frame, 3, y + 3, "   value", "factValue"),
            checkbox(frame, 3, y + 4, "   context", "factCntx"),
            checkbox(frame, 3, y + 5, "   unit", "factUnit"),
            checkbox(frame, 3, y + 6, "Messages", "messagesLog"),

            # Note: if adding to this list keep Finder.FindOptions in sync
        )
        y += 7
        resultLabel = gridHdr(frame, 1, y, "Result:", anchor="w")
        resultLabel.grid(padx=8)
        self.resultText = gridCell(frame, 1, y + 1)
        self.resultText.grid(columnspan=3, padx=8)
        self.resultText.config(state="readonly")
        y += 2

        mainWin.showStatus(None)

        buttonFrame = Frame(frame)
        buttonFrame.grid(columnspan=4, sticky=E, padx=8)
        findButton = Button(buttonFrame,
                            text=_("Find"),
                            width=12,
                            command=self.find)
        ToolTip(
            findButton,
            text=
            _('Compile (if regular expression or XPath 2), and find first match (if down direction) or last match (if up direction).  '
              ),
            wraplength=240)
        nextButton = Button(buttonFrame,
                            text=_("Next"),
                            width=12,
                            command=self.next)
        ToolTip(
            nextButton,
            text=_(
                'Advance to the next matched object (in selected direction).  '
            ),
            wraplength=240)
        closeButton = Button(buttonFrame,
                             text=_("Close"),
                             width=12,
                             command=self.close)
        ToolTip(closeButton,
                text=_('Close the find dialog.  '),
                wraplength=240)
        findButton.grid(row=1, column=1, pady=3)
        nextButton.grid(row=1, column=2, pady=3)
        closeButton.grid(row=1, column=3, padx=3)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(1, weight=1)
        frame.columnconfigure(2, weight=1)
        frame.columnconfigure(3, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        if self.options["geometry"]:
            self.geometry(self.options["geometry"])
        else:
            self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)

        self.protocol("WM_DELETE_WINDOW", self.close)

        # make this dialog non-modal
        self.focus_set()
Beispiel #37
0
class ViewGrid:
    def __init__(self,
                 modelXbrl,
                 tabWin,
                 tabTitle,
                 hasToolTip=False,
                 lang=None):
        self.tabWin = tabWin
        #self.viewFrame = Frame(tabWin)
        #self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        '''
        paneWin = PanedWindow(self.viewFrame, orient=VERTICAL)
        paneWin.grid(row=1, column=0, sticky=(N, S, E, W))
        self.zGrid = scrollgrid(paneWin)
        self.zGrid.grid(row=0, column=0, sticky=(N, S, E, W))
        self.xyGrid = scrollgrid(paneWin)
        self.xyGrid.grid(row=1, column=0, sticky=(N, S, E, W))
        '''
        '''
        self.gridBody = scrollgrid(self.viewFrame)
        self.gridBody.grid(row=0, column=0, sticky=(N, S, E, W))
        '''

        self.viewFrame = scrolledHeaderedFrame(tabWin)
        self.gridTblHdr = self.viewFrame.tblHdrInterior
        self.gridColHdr = self.viewFrame.colHdrInterior
        self.gridRowHdr = self.viewFrame.rowHdrInterior
        self.gridBody = self.viewFrame.bodyInterior
        '''
        self.viewFrame = scrolledFrame(tabWin)
        self.gridTblHdr = self.gridRowHdr = self.gridColHdr = self.gridBody = self.viewFrame.interior
        '''

        tabWin.add(self.viewFrame, text=tabTitle)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.gridBody.bind("<Motion>", self.motion, '+')
            self.gridBody.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.gridBody,
                                   textvariable=self.toolTipText,
                                   wraplength=480,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        self.contextMenuClick = self.modelXbrl.modelManager.cntlr.contextMenuClick
        self.gridTblHdr.contextMenuClick = self.contextMenuClick
        self.gridColHdr.contextMenuClick = self.contextMenuClick
        self.gridRowHdr.contextMenuClick = self.contextMenuClick
        self.gridBody.contextMenuClick = self.contextMenuClick
        self.lang = lang
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang:
                self.lang = modelXbrl.modelManager.defaultLang

    def close(self):
        self.tabWin.forget(self.viewFrame)
        if self in self.modelXbrl.views:
            self.modelXbrl.views.remove(self)
        self.modelXbrl = None

    def select(self):
        self.tabWin.select(self.viewFrame)

    def leave(self, *args):
        self.toolTipColId = None
        self.toolTipRowId = None

    def motion(self, *args):
        '''
        tvColId = self.gridBody.identify_column(args[0].x)
        tvRowId = self.gridBody.identify_row(args[0].y)
        if tvColId != self.toolTipColId or tvRowId != self.toolTipRowId:
            self.toolTipColId = tvColId
            self.toolTipRowId = tvRowId
            newValue = None
            if tvRowId and len(tvRowId) > 0:
                try:
                    col = int(tvColId[1:])
                    if col == 0:
                        newValue = self.gridBody.item(tvRowId,"text")
                    else:
                        values = self.gridBody.item(tvRowId,"values")
                        if col <= len(values):
                            newValue = values[col - 1]
                except ValueError:
                    pass
            self.setToolTip(newValue, tvColId)
        '''

    def setToolTip(self, text, colId="#0"):
        self.toolTip._hide()
        if isinstance(text, str) and len(text) > 0:
            width = self.gridBody.column(colId, "width")
            if len(text) * 8 > width or '\n' in text:
                self.toolTipText.set(text)
                self.toolTip.configure(state="normal")
                self.toolTip._schedule()
            else:
                self.toolTipText.set("")
                self.toolTip.configure(state="disabled")
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")

    def contextMenu(self):
        try:
            return self.menu
        except AttributeError:
            self.menu = Menu(self.viewFrame, tearoff=0)
            self.gridBody.bind(self.contextMenuClick, self.popUpMenu)
            if not self.gridTblHdr.bind(self.contextMenuClick):
                self.gridTblHdr.bind(self.contextMenuClick, self.popUpMenu)
            if not self.gridColHdr.bind(self.contextMenuClick):
                self.gridColHdr.bind(self.contextMenuClick, self.popUpMenu)
            if not self.gridRowHdr.bind(self.contextMenuClick):
                self.gridRowHdr.bind(self.contextMenuClick, self.popUpMenu)
            return self.menu

    def popUpMenu(self, event):
        self.menu.post(event.x_root, event.y_root)

    def menuAddLangs(self):
        langsMenu = Menu(self.viewFrame, tearoff=0)
        self.menu.add_cascade(label=_("Language"), menu=langsMenu, underline=0)
        for lang in sorted(self.modelXbrl.langs):
            langsMenu.add_cascade(label=lang,
                                  underline=0,
                                  command=lambda l=lang: self.setLang(l))

    def setLang(self, lang):
        self.lang = lang
        self.view()
Beispiel #38
0
    def __init__(self, parent, title, host=None, realm=None, useOsProxy=None, urlAddr=None, urlPort=None, user=None, password=None, showUrl=False, showUser=False, showHost=True, showRealm=True):
        super().__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)", parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False
        self.transient(self.parent)
        self.title(title)
        self.urlAddrVar = StringVar()
        self.urlAddrVar.set(urlAddr if urlAddr else "")
        self.urlPortVar = StringVar()
        self.urlPortVar.set(urlPort if urlPort else "")
        self.userVar = StringVar()
        self.userVar.set(user if user else "")
        self.passwordVar = StringVar()
        self.passwordVar.set(password if password else "")
        
        frame = Frame(self)
        y = 0
        if showHost:
            hostLabel = Label(frame, text=_("Host:"), underline=0)
            hostDisplay = Label(frame, text=host, width=30)
            if host and len(host) > 30:
                ToolTip(hostDisplay, text=host, wraplength=240)
            hostLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            hostDisplay.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
            y += 1
        if showRealm:
            realmLabel = Label(frame, text=_("Realm:"), underline=0)
            realmDisplay = Label(frame, text=realm, width=25)
            if realm and len(realm) > 30:
                ToolTip(realmDisplay, text=realm, wraplength=240)
            realmLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            realmDisplay.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
            y += 1
        self.enabledWidgets = []
        if useOsProxy is not None:
            if sys.platform.startswith("win"):
                hostProxy = _('Microsoft Windows Internet Settings')
            elif sys.platform in ("darwin", "macos"):
                hostProxy = _('Mac OS X System Configuration')
            else: # linux/unix
                hostProxy = _('environment variables')
            useOsProxyCb = checkbox(frame, 0, y, text=_("Use proxy server of {0}").format(hostProxy))
            useOsProxyCb.grid(columnspan=5)
            useOsProxyCb.valueVar.set(useOsProxy)
            ToolTip(useOsProxyCb, text=_("Check to use {0} \n"
                                         "Uncheck to specify: \n"
                                         "   No proxy if URL address is left blank, \n"
                                         "   Proxy via URL address if it is not blank, \n"
                                         "       with user and password (if provided)"
                                         .format(hostProxy)), wraplength=360)
            self.useOsProxyCb = useOsProxyCb
            useOsProxyCb.valueVar.trace("w", self.setEnabledState)

            y += 1
        if showUrl:
            urlAddrLabel = Label(frame, text=_("Address:"), underline=0)
            urlAddrEntry = Entry(frame, textvariable=self.urlAddrVar, width=16)
            urlPortLabel = Label(frame, text=_("Port:"), underline=0)
            urlPortEntry = Entry(frame, textvariable=self.urlPortVar, width=5)
            urlAddrEntry.focus_set()
            urlAddrLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
            urlAddrEntry.grid(row=y, column=1, columnspan=2, sticky=EW, pady=3, padx=3)
            urlPortLabel.grid(row=y, column=3, sticky=W, pady=3, padx=3)
            urlPortEntry.grid(row=y, column=4, sticky=EW, pady=3, padx=3)
            ToolTip(urlAddrEntry, text=_("Enter URL address and port number \n"
                                         "  e.g., address: 168.1.2.3 port: 8080 \n"
                                         "  or address: proxy.myCompany.com port: 8080 \n"
                                         "  or leave blank to specify no proxy server"), wraplength=360)
            self.enabledWidgets.append(urlAddrEntry)
            self.enabledWidgets.append(urlPortEntry)
            y += 1
        userLabel = Label(frame, text=_("User:"******"Password:"******"*")
        passwordLabel.grid(row=y, column=0, sticky=W, pady=3, padx=3)
        passwordEntry.grid(row=y, column=1, columnspan=4, sticky=EW, pady=3, padx=3)
        self.enabledWidgets.append(passwordEntry)
        y += 1
        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=E, pady=3)
        cancelButton.grid(row=y, column=3, columnspan=2, sticky=EW, pady=3, padx=3)
        y += 1
                
        if useOsProxy is not None:
            self.setEnabledState()

        frame.grid(row=0, column=0, sticky=(N,S,E,W))
        frame.columnconfigure(1, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX+50,dialogY+100))
        
        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)
        
        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)
Beispiel #39
0
    def __init__(self, mainWin):
        parent = mainWin.parent
        super(DialogTransformTester, self).__init__(parent)
        self.mainWin = mainWin
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.selectedGroup = None

        self.transient(self.parent)
        self.title(_("Transformation Tester"))

        frame = Frame(self)

        # setup tester
        xml = "<rootElement/>"
        self.modelXbrl = ModelXbrl.create(mainWin.modelManager,
                                          ModelDocument.Type.UnknownNonXML,
                                          initialXml=xml,
                                          isEntry=True)
        self.validator = ValidateXbrl.ValidateXbrl(self.modelXbrl)
        self.validator.validate(self.modelXbrl)  # required to set up
        mainWin.showStatus(_("Initializing Formula Grammar"))
        XPathParser.initializeParser(mainWin.modelManager)
        mainWin.showStatus(None)

        self.trRegs = sorted(ixtNamespaces.keys())
        self.trReg = self.trRegs[-1]  # default is latest
        self.trPrefixNSs = dict(
            (qn.prefix, qn.namespaceURI)
            for qn in self.modelXbrl.modelManager.customTransforms.keys())
        self.trRegs.extend(sorted(self.trPrefixNSs.keys()))
        self.trPrefixNSs.update(ixtNamespaces)
        self.trNames = self.getTrNames()

        # load grid
        trRegLabel = label(frame, 0, 0, _("Registry:"))
        self.trRegName = gridCombobox(
            frame,
            1,
            0,
            value=self.trReg,
            values=self.trRegs,
            comboboxselected=self.trRegComboBoxSelected)
        trRegToolTipMessage = _("Select Transformation Registry")
        ToolTip(self.trRegName, text=trRegToolTipMessage, wraplength=360)
        ToolTip(trRegLabel, text=trRegToolTipMessage, wraplength=360)

        trNameLabel = label(frame, 0, 1, _("Transform:"))
        self.trNameName = gridCombobox(
            frame,
            1,
            1,
            value="",
            values=self.trNames,
            comboboxselected=self.trNameComboBoxSelected)
        trRegToolTipMessage = _("Select or enter transform")
        ToolTip(self.trRegName, text=trRegToolTipMessage, wraplength=360)
        ToolTip(trRegLabel, text=trRegToolTipMessage, wraplength=360)

        sourceLabel = label(frame, 0, 2, _("Source text:"))
        ToolTip(sourceLabel,
                text=_("Enter the source text which is to be transformed. "),
                wraplength=240)
        self.sourceVar = StringVar()
        self.sourceVar.set("")
        sourceEntry = Entry(frame, textvariable=self.sourceVar, width=50)
        sourceLabel.grid(row=2, column=0, sticky=W)
        sourceEntry.grid(row=2, column=1, sticky=EW, pady=3, padx=3)

        resultLabel = label(frame, 1, 3, _("Result:"))
        ToolTip(sourceLabel, text=_("Transformation result. "), wraplength=240)
        self.resultVar = StringVar()
        self.resultVar.set("")
        resultEntry = Entry(frame, textvariable=self.resultVar, width=50)
        resultLabel.grid(row=3, column=0, sticky=W)
        resultEntry.grid(row=3, column=1, sticky=EW, pady=3, padx=3)

        mainWin.showStatus(None)

        btnPad = 2 if mainWin.isMSW else 0  # buttons too narrow on windows
        okButton = Button(frame,
                          text=_("Transform"),
                          width=8 + btnPad,
                          command=self.ok)
        cancelButton = Button(frame,
                              text=_("Done"),
                              width=4 + btnPad,
                              command=self.close)
        cancelButton.grid(row=4,
                          column=0,
                          sticky=E,
                          columnspan=2,
                          pady=3,
                          padx=3)
        okButton.grid(row=4, column=0, sticky=E, columnspan=2, pady=3, padx=64)
        ToolTip(okButton,
                text=_("Transform the source entered. "),
                wraplength=240)
        ToolTip(cancelButton, text=_("Close this dialog. "), wraplength=240)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(1, weight=3)
        frame.columnconfigure(2, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 150, dialogY + 100))

        #self.bind("<Return>", self.ok)
        #self.bind("<Escape>", self.close)

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()

        self.wait_window(self)
Beispiel #40
0
class ViewTree:
    def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False, lang=None):
        self.tabWin = tabWin
        self.viewFrame = Frame(tabWin)
        self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        tabWin.add(self.viewFrame,text=tabTitle)
        vScrollbar = Scrollbar(self.viewFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(self.viewFrame, orient=HORIZONTAL)
        self.treeView = Treeview(self.viewFrame, xscrollcommand=hScrollbar.set, yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        self.treeView.tag_configure("ELR", background="#E0F0FF")
        self.treeView.tag_configure("even", background="#F0F0F0")
        self.treeView.tag_configure("odd", background="#FFFFFF")
        highlightColor = "#%04x%04x%04x" % self.treeView.winfo_rgb("SystemHighlight")
        self.treeView.tag_configure("selected-ELR", background=highlightColor)
        self.treeView.tag_configure("selected-even", background=highlightColor)
        self.treeView.tag_configure("selected-odd", background=highlightColor)
        self.treeViewSelection = ()
        self.treeView.bind("<<TreeviewSelect>>", self.treeViewSelectionChange, '+')
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E,W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N,S))
        self.viewFrame.columnconfigure(0, weight=1)
        self.viewFrame.rowconfigure(0, weight=1)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView, 
                                   textvariable=self.toolTipText, 
                                   wraplength=480, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        self.lang = lang
        self.labelrole = None
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang: 
                self.lang = modelXbrl.modelManager.defaultLang
                
    def treeViewSelectionChange(self, event=None):
        for node in self.treeViewSelection:
            priorTags = self.treeView.item(node)["tags"]
            if priorTags:
                priorBgTag = priorTags[0]
                if priorBgTag.startswith("selected-"):
                    self.treeView.item(node, tags=(priorBgTag[9:],))
        self.treeViewSelection = self.treeView.selection()
        for node in self.treeViewSelection:
            priorTags = self.treeView.item(node)["tags"]
            if priorTags:
                self.treeView.item(node, tags=("selected-" + priorTags[0],))
            
    def close(self):
        if self.modelXbrl:
            self.tabWin.forget(self.viewFrame)
            self.modelXbrl.views.remove(self)
            self.modelXbrl = None
        
    def leave(self, *args):
        self.toolTipColId = None
        self.toolTipRowId = None

    def motion(self, *args):
        tvColId = self.treeView.identify_column(args[0].x)
        tvRowId = self.treeView.identify_row(args[0].y)
        if tvColId != self.toolTipColId or tvRowId != self.toolTipRowId:
            self.toolTipColId = tvColId
            self.toolTipRowId = tvRowId
            newValue = None
            if tvRowId and len(tvRowId) > 0:
                try:
                    col = int(tvColId[1:])
                    if col == 0:
                        newValue = self.treeView.item(tvRowId,"text")
                    else:
                        values = self.treeView.item(tvRowId,"values")
                        if col <= len(values):
                            newValue = values[col - 1]
                except ValueError:
                    pass
            self.setToolTip(newValue, tvColId)
                
    def setToolTip(self, text, colId="#0"):
        self.toolTip._hide()
        if isinstance(text,str) and len(text) > 0:
            width = self.treeView.column(colId,"width")
            if len(text) * 8 > width or '\n' in text:
                self.toolTipText.set(text)
                self.toolTip.configure(state="normal")
                self.toolTip._schedule()
            else:
                self.toolTipText.set("")
                self.toolTip.configure(state="disabled")
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")

    def contextMenu(self):
        try:
            return self.menu
        except AttributeError:
            self.menu = Menu( self.viewFrame, tearoff = 0 )
            self.treeView.bind( self.modelXbrl.modelManager.cntlr.contextMenuClick, self.popUpMenu, '+' )
            return self.menu

    def popUpMenu(self, event):
        self.menuRow = self.treeView.identify_row(event.y)
        self.menuCol = self.treeView.identify_column(event.x)
        self.menu.post( event.x_root, event.y_root )
        
    def expand(self):
        self.setTreeItemOpen(self.menuRow,open=True)
        
    def expandAll(self):
        self.setTreeItemOpen("",open=True)
        
    def collapse(self):
        self.setTreeItemOpen(self.menuRow,open=False)
        
    def collapseAll(self):
        self.setTreeItemOpen("",open=False)
        
    def setTreeItemOpen(self, node, open=True):
        if node:
            self.treeView.item(node, open=open)
        for childNode in self.treeView.get_children(node):
            self.setTreeItemOpen(childNode, open)
            
    def menuAddExpandCollapse(self):
        self.menu.add_cascade(label=_("Expand"), underline=0, command=self.expand)
        self.menu.add_cascade(label=_("Collapse"), underline=0, command=self.collapse)
        self.menu.add_cascade(label=_("Expand All"), underline=0, command=self.expandAll)
        self.menu.add_cascade(label=_("Collapse All"), underline=0, command=self.collapseAll)
        
    def menuAddClipboard(self):
        if self.modelXbrl.modelManager.cntlr.hasClipboard:
            clipboardMenu = Menu(self.viewFrame, tearoff=0)
            clipboardMenu.add_cascade(label=_("Cell"), underline=0, command=self.copyCellToClipboard)
            clipboardMenu.add_cascade(label=_("Row"), underline=0, command=self.copyRowToClipboard)
            clipboardMenu.add_cascade(label=_("Table"), underline=0, command=self.copyTableToClipboard)
            self.menu.add_cascade(label=_("Copy to clipboard"), menu=clipboardMenu, underline=0)
        
    def menuAddLangs(self):
        langsMenu = Menu(self.viewFrame, tearoff=0)
        self.menu.add_cascade(label=_("Language"), menu=langsMenu, underline=0)
        for lang in sorted(self.modelXbrl.langs):
            langsMenu.add_cascade(label=lang, underline=0, command=lambda l=lang: self.setLang(l))

    def menuAddLabelRoles(self, includeConceptName=False, menulabel=None):
        if menulabel is None: menulabel = _("Label Role")
        rolesMenu = Menu(self.viewFrame, tearoff=0)
        self.menu.add_cascade(label=menulabel, menu=rolesMenu, underline=0)
        from arelle.ModelRelationshipSet import labelroles
        for x in labelroles(self.modelXbrl, includeConceptName):
            rolesMenu.add_cascade(label=x[0][1:], underline=0, command=lambda a=x[1]: self.setLabelrole(a))

    def menuAddUnitDisplay(self):
        rolesMenu = Menu(self.viewFrame, tearoff=0)
        self.menu.add_cascade(label=_("Units"), menu=rolesMenu, underline=0)
        rolesMenu.add_cascade(label=_("Unit ID"), underline=0, command=lambda: self.setUnitDisplay(unitDisplayID=True))
        rolesMenu.add_cascade(label=_("Measures"), underline=0, command=lambda: self.setUnitDisplay(unitDisplayID=False))

    def menuAddViews(self):
        viewMenu = Menu(self.viewFrame, tearoff=0)
        self.menu.add_cascade(label=_("View"), menu=viewMenu, underline=0)
        newViewsMenu = Menu(self.viewFrame, tearoff=0)
        viewMenu.add_cascade(label=_("Close"), underline=0, command=self.close)
        viewMenu.add_cascade(label=_("Additional view"), menu=newViewsMenu, underline=0)
        from arelle.ModelRelationshipSet import baseSetArcroles
        for x in baseSetArcroles(self.modelXbrl):
            newViewsMenu.add_cascade(label=x[0][1:], underline=0, command=lambda a=x[1]: self.newView(a))
    
    def newView(self, arcrole):
        from arelle import ViewWinRelationshipSet
        ViewWinRelationshipSet.viewRelationshipSet(self.modelXbrl, self.tabWin, arcrole, lang=self.lang)
            
    def setLang(self, lang):
        self.lang = lang
        self.view()
        
    def setLabelrole(self, labelrole):
        self.labelrole = labelrole
        self.view()
        
    def setUnitDisplay(self, unitDisplayID=False):
        self.unitDisplayID = unitDisplayID
        self.view()
        
    def setColumnsSortable(self, treeColIsInt=False, startUnsorted=False, initialSortCol="#0", initialSortDirForward=True):
        self.lastSortColumn = None if startUnsorted else initialSortCol 
        self.lastSortColumnForward = initialSortDirForward
        self.treeColIsInt = treeColIsInt
        if not hasattr(self, "sortImages"):
            self.sortImages = (PhotoImage(file=os.path.join(self.modelXbrl.modelManager.cntlr.imagesDir, "columnSortUp.gif")),
                               PhotoImage(file=os.path.join(self.modelXbrl.modelManager.cntlr.imagesDir, "columnSortDown.gif")),
                               PhotoImage())
        for col in ("#0",) + self.treeView["columns"]:
            self.treeView.heading(col, command=lambda c=col: self.sortColumn(c))
        if not startUnsorted:
            self.treeView.heading(initialSortCol, image=self.sortImages[not initialSortDirForward])
            
    def colSortVal(self, node, col):
        if col == "#0":
            treeColVal = self.treeView.item(node)["text"]
            if self.treeColIsInt: 
                return int(treeColVal)
        else:
            treeColVal = self.treeView.set(node, col)
            if col == "sequence":
                try:
                    return int(treeColVal)
                except:
                    return 0
        return treeColVal
    
    def sortNestedRows(self, parentNode, col, reverse):
        l = [(self.colSortVal(node, col), node) for node in self.treeView.get_children(parentNode)]
        l.sort(reverse=reverse)
        # rearrange items in sorted positions     
        for i, (cell, node) in enumerate(l):         
            self.treeView.move(node, parentNode, i)
        # reset even/odd tags
        for i, node in enumerate(self.treeView.get_children(parentNode)):
            self.treeView.item(node, tags=('even' if i & 1 else 'odd',))
            self.sortNestedRows(node, col, reverse)
                    
    def sortColumn(self, col):
        if col == self.lastSortColumn:
            reverse = self.lastSortColumnForward
            self.lastSortColumnForward = not reverse
        else:
            if self.lastSortColumn:
                self.treeView.heading(self.lastSortColumn, image=self.sortImages[2])
            reverse = False
            self.lastSortColumnForward = True
            self.lastSortColumn = col
        self.treeView.heading(col, image=self.sortImages[reverse])
        self.sortNestedRows('', col, reverse)
        self.treeViewSelectionChange()  # reselect selected rows
        
    def copyCellToClipboard(self, *ignore):
        self.modelXbrl.modelManager.cntlr.clipboardData(
            text=self.treeView.item(self.menuRow)['text'] if self.menuCol == '#0' else self.treeView.set(self.menuRow,self.menuCol))
        
    def copyRowToClipboard(self, *ignore):
        self.modelXbrl.modelManager.cntlr.clipboardData(
            text='\t'.join([self.treeView.item(self.menuRow)['text']] +
                           [self.treeView.set(self.menuRow,c) for c in self.treeView['columns']]))
        
    def copyTableToClipboard(self, *ignore):
        cols = self.treeView['columns']
        lines = ['\t'.join([self.treeView.heading('#0')['text']] +
                           [self.treeView.heading(h)['text'] for h in cols])]
        self.tabLines('', '', cols, lines)
        self.modelXbrl.modelManager.cntlr.clipboardData(text='\n'.join(lines))

    def tabLines(self, parentNode, indent, cols, lines): 
        for node in self.treeView.get_children(parentNode):
            lines.append('\t'.join([indent + self.treeView.item(node)['text']] +
                                   [self.treeView.set(node,c) for c in cols]))
            self.tabLines(node, indent+'    ', cols, lines)
Beispiel #41
0
class ViewGrid:
    def __init__(self, modelXbrl, tabWin, tabTitle, hasToolTip=False, lang=None):
        self.tabWin = tabWin
        #self.viewFrame = Frame(tabWin)
        #self.viewFrame.grid(row=0, column=0, sticky=(N, S, E, W))
        '''
        paneWin = PanedWindow(self.viewFrame, orient=VERTICAL)
        paneWin.grid(row=1, column=0, sticky=(N, S, E, W))
        self.zGrid = scrollgrid(paneWin)
        self.zGrid.grid(row=0, column=0, sticky=(N, S, E, W))
        self.xyGrid = scrollgrid(paneWin)
        self.xyGrid.grid(row=1, column=0, sticky=(N, S, E, W))
        '''
        '''
        self.gridBody = scrollgrid(self.viewFrame)
        self.gridBody.grid(row=0, column=0, sticky=(N, S, E, W))
        '''
        
        self.viewFrame = scrolledHeaderedFrame(tabWin)
        self.gridTblHdr = self.viewFrame.tblHdrInterior
        self.gridColHdr = self.viewFrame.colHdrInterior
        self.gridRowHdr = self.viewFrame.rowHdrInterior
        self.gridBody = self.viewFrame.bodyInterior
        '''
        self.viewFrame = scrolledFrame(tabWin)
        self.gridTblHdr = self.gridRowHdr = self.gridColHdr = self.gridBody = self.viewFrame.interior
        '''
        
        tabWin.add(self.viewFrame,text=tabTitle)
        self.modelXbrl = modelXbrl
        self.hasToolTip = hasToolTip
        self.toolTipText = StringVar()
        if hasToolTip:
            self.gridBody.bind("<Motion>", self.motion, '+')
            self.gridBody.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.gridBody, 
                                   textvariable=self.toolTipText, 
                                   wraplength=480, 
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipColId = None
            self.toolTipRowId = None
        self.modelXbrl = modelXbrl
        self.contextMenuClick = self.modelXbrl.modelManager.cntlr.contextMenuClick
        self.gridTblHdr.contextMenuClick = self.contextMenuClick
        self.gridColHdr.contextMenuClick = self.contextMenuClick
        self.gridRowHdr.contextMenuClick = self.contextMenuClick
        self.gridBody.contextMenuClick = self.contextMenuClick
        self.lang = lang
        if modelXbrl:
            modelXbrl.views.append(self)
            if not lang: 
                self.lang = modelXbrl.modelManager.defaultLang
        
    def close(self):
        self.tabWin.forget(self.viewFrame)
        self.modelXbrl.views.remove(self)
        self.modelXbrl = None
        
    def leave(self, *args):
        self.toolTipColId = None
        self.toolTipRowId = None

    def motion(self, *args):
        '''
        tvColId = self.gridBody.identify_column(args[0].x)
        tvRowId = self.gridBody.identify_row(args[0].y)
        if tvColId != self.toolTipColId or tvRowId != self.toolTipRowId:
            self.toolTipColId = tvColId
            self.toolTipRowId = tvRowId
            newValue = None
            if tvRowId and len(tvRowId) > 0:
                try:
                    col = int(tvColId[1:])
                    if col == 0:
                        newValue = self.gridBody.item(tvRowId,"text")
                    else:
                        values = self.gridBody.item(tvRowId,"values")
                        if col <= len(values):
                            newValue = values[col - 1]
                except ValueError:
                    pass
            self.setToolTip(newValue, tvColId)
        '''
                
    def setToolTip(self, text, colId="#0"):
        self.toolTip._hide()
        if isinstance(text,str) and len(text) > 0:
            width = self.gridBody.column(colId,"width")
            if len(text) * 8 > width or '\n' in text:
                self.toolTipText.set(text)
                self.toolTip.configure(state="normal")
                self.toolTip._schedule()
            else:
                self.toolTipText.set("")
                self.toolTip.configure(state="disabled")
        else:
            self.toolTipText.set("")
            self.toolTip.configure(state="disabled")

    def contextMenu(self):
        try:
            return self.menu
        except AttributeError:
            self.menu = Menu( self.viewFrame, tearoff = 0 )
            self.gridBody.bind( self.contextMenuClick, self.popUpMenu )
            if not self.gridTblHdr.bind(self.contextMenuClick): 
                self.gridTblHdr.bind( self.contextMenuClick, self.popUpMenu )
            if not self.gridColHdr.bind(self.contextMenuClick): 
                self.gridColHdr.bind( self.contextMenuClick, self.popUpMenu )
            if not self.gridRowHdr.bind(self.contextMenuClick): 
                self.gridRowHdr.bind( self.contextMenuClick, self.popUpMenu )
            return self.menu

    def popUpMenu(self, event):
        self.menu.post( event.x_root, event.y_root )
        
    def menuAddLangs(self):
        langsMenu = Menu(self.viewFrame, tearoff=0)
        self.menu.add_cascade(label=_("Language"), menu=langsMenu, underline=0)
        for lang in sorted(self.modelXbrl.langs):
            langsMenu.add_cascade(label=lang, underline=0, command=lambda l=lang: self.setLang(l))
    
    def setLang(self, lang):
        self.lang = lang
        self.view()
    def __init__(self,
                 parent,
                 openType,
                 filesource,
                 filenames,
                 title,
                 colHeader,
                 showAltViewButton=False):
        if isinstance(parent, Cntlr):
            cntlr = parent
            parent = parent.parent  # parent is cntlrWinMain
        else:  # parent is a Toplevel dialog
            cntlr = parent.cntlr
        super(DialogOpenArchive, self).__init__(parent)
        self.parent = parent
        self.showAltViewButton = showAltViewButton
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        self.selection = filesource.selection
        self.hasToolTip = False
        selectedNode = None

        if openType == ENTRY_POINTS:
            try:
                metadataFiles = filesource.taxonomyPackageMetadataFiles
                ''' take first for now
                if len(metadataFiles) != 1:
                    raise IOError(_("Taxonomy package contained more than one metadata file: {0}.")
                                  .format(', '.join(metadataFiles)))
                '''
                metadataFile = metadataFiles[0]
                metadata = filesource.url + os.sep + metadataFile
                self.metadataFilePrefix = os.sep.join(
                    os.path.split(metadataFile)[:-1])
                if self.metadataFilePrefix:
                    self.metadataFilePrefix += "/"  # zip contents have /, never \ file seps
                self.taxonomyPkgMetaInf = '{}/META-INF/'.format(
                    os.path.splitext(os.path.basename(filesource.url))[0])

                self.taxonomyPackage = parsePackage(
                    cntlr, filesource, metadata,
                    os.sep.join(os.path.split(metadata)[:-1]) + os.sep)

                if self.taxonomyPackage["entryPoints"]:
                    # may have instance documents too
                    self.packageContainedInstances = []
                    packageContentTypeCounts = {}
                    for suffix in (".xhtml", ".htm", ".html"):
                        for potentialInstance in filesource.dir:
                            if potentialInstance.endswith(".xhtml"):
                                _type = "Inline Instance"
                                self.packageContainedInstances.append(
                                    [potentialInstance, _type])
                                packageContentTypeCounts[
                                    potentialInstance] = packageContentTypeCounts.get(
                                        potentialInstance, 0) + 1
                        if self.packageContainedInstances:
                            break
                    if self.packageContainedInstances:  # add sequences to any duplicated entry types
                        for _type, count in packageContentTypeCounts.items():
                            if count > 1:
                                _dupNo = 0
                                for i in range(
                                        len(self.packageContainedInstances)):
                                    if self.packageContainedInstances[i][
                                            0] == _type:
                                        _dupNo += 1
                                        self.packageContainedInstances[i][
                                            0] = "{} {}".format(_type, _dupNo)

                else:
                    # may be a catalog file with no entry oint names
                    openType = ARCHIVE  # no entry points to show, just archive
                    self.showAltViewButton = False
            except Exception as e:
                self.close()
                err = _(
                    "Failed to parse metadata; the underlying error was: {0}"
                ).format(e)
                messagebox.showerror(_("Malformed taxonomy package"), err)
                cntlr.addToLog(err)
                return

        if openType not in (PLUGIN, PACKAGE):
            cntlr.showStatus(None)

        if openType in (DISCLOSURE_SYSTEM, PLUGIN, PACKAGE):
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        if self.showAltViewButton:
            self.altViewButton = Button(frame, command=self.showAltView)
            self.altViewButton.grid(row=y,
                                    column=0,
                                    sticky=(S, W),
                                    pady=3,
                                    padx=3)

        self.loadTreeView(openType, colHeader, title)

        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))
        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        frame.rowconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        window.rowconfigure(0, weight=1)

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if self.hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()

        self.wait_window(self)
Beispiel #43
0
    def __init__(self, mainWin, openType, filesource, filenames, title,
                 colHeader):
        parent = mainWin.parent
        super().__init__(parent)
        self.parent = parent
        parentGeometry = re.match("(\d+)x(\d+)[+]?([-]?\d+)[+]?([-]?\d+)",
                                  parent.geometry())
        dialogX = int(parentGeometry.group(3))
        dialogY = int(parentGeometry.group(4))
        self.accepted = False

        self.transient(self.parent)
        self.title(title)

        frame = Frame(self)

        treeFrame = Frame(frame, width=500)
        vScrollbar = Scrollbar(treeFrame, orient=VERTICAL)
        hScrollbar = Scrollbar(treeFrame, orient=HORIZONTAL)
        self.treeView = Treeview(treeFrame,
                                 xscrollcommand=hScrollbar.set,
                                 yscrollcommand=vScrollbar.set)
        self.treeView.grid(row=0, column=0, sticky=(N, S, E, W))
        hScrollbar["command"] = self.treeView.xview
        hScrollbar.grid(row=1, column=0, sticky=(E, W))
        vScrollbar["command"] = self.treeView.yview
        vScrollbar.grid(row=0, column=1, sticky=(N, S))
        treeFrame.columnconfigure(0, weight=1)
        treeFrame.rowconfigure(0, weight=1)
        treeFrame.grid(row=0,
                       column=0,
                       columnspan=4,
                       sticky=(N, S, E, W),
                       padx=3,
                       pady=3)
        self.treeView.focus_set()

        # set up treeView widget and tabbed pane
        self.treeView.column("#0", width=500, anchor="w")
        self.treeView.heading("#0", text=colHeader)
        try:
            self.isRss = filesource.isRss
            if self.isRss:
                self.treeView.column("#0", width=350, anchor="w")
                self.treeView["columns"] = ("descr", "date", "instDoc")
                self.treeView.column("descr",
                                     width=50,
                                     anchor="center",
                                     stretch=False)
                self.treeView.heading("descr", text="Form")
                self.treeView.column("date",
                                     width=170,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("date", text="Pub Date")
                self.treeView.column("instDoc",
                                     width=200,
                                     anchor="w",
                                     stretch=False)
                self.treeView.heading("instDoc", text="Instance Document")
        except AttributeError:
            self.isRss = False

        mainWin.showStatus(_("loading archive {0}").format(filesource.url))
        self.filesource = filesource
        self.filenames = filenames
        selection = filesource.selection
        hasToolTip = False
        loadedPaths = []
        i = 0
        selectedNode = None
        for filename in self.filenames:
            if isinstance(filename, tuple):
                if self.isRss:
                    form, date, instDoc = filename[2:5]
                filename = filename[0]  # ignore tooltip
                hasToolTip = True
            if filename.endswith("/"):
                filename = filename[:-1]
            path = filename.split("/")
            if not self.isRss and len(path) > 1 and path[:-1] in loadedPaths:
                parent = "file{0}".format(loadedPaths.index(path[:-1]))
            else:
                parent = ""
            node = self.treeView.insert(parent,
                                        "end",
                                        "file{0}".format(i),
                                        text=path[-1])
            if self.isRss:
                self.treeView.set(node, "descr", form)
                self.treeView.set(node, "date", date)
                self.treeView.set(node, "instDoc", os.path.basename(instDoc))
            if selection == filename:
                selectedNode = node
            loadedPaths.append(path)
            i += 1
        if selectedNode:
            self.treeView.see(selectedNode)
            self.treeView.selection_set(selectedNode)
        mainWin.showStatus(None)

        if openType == DISCLOSURE_SYSTEM:
            y = 3
        else:
            y = 1

        okButton = Button(frame, text=_("OK"), command=self.ok)
        cancelButton = Button(frame, text=_("Cancel"), command=self.close)
        okButton.grid(row=y, column=2, sticky=(S, E, W), pady=3)
        cancelButton.grid(row=y, column=3, sticky=(S, E, W), pady=3, padx=3)

        frame.grid(row=0, column=0, sticky=(N, S, E, W))
        frame.columnconfigure(0, weight=1)
        window = self.winfo_toplevel()
        window.columnconfigure(0, weight=1)
        self.geometry("+{0}+{1}".format(dialogX + 50, dialogY + 100))

        self.bind("<Return>", self.ok)
        self.bind("<Escape>", self.close)

        self.toolTipText = StringVar()
        if hasToolTip:
            self.treeView.bind("<Motion>", self.motion, '+')
            self.treeView.bind("<Leave>", self.leave, '+')
            self.toolTipText = StringVar()
            self.toolTip = ToolTip(self.treeView,
                                   textvariable=self.toolTipText,
                                   wraplength=640,
                                   follow_mouse=True,
                                   state="disabled")
            self.toolTipRowId = None

        self.protocol("WM_DELETE_WINDOW", self.close)
        self.grab_set()
        self.wait_window(self)