Example #1
0
class DataBasePanel(scrolled.ScrolledPanel):
    def __init__(self, parent, statusbar):
        scrolled.ScrolledPanel.__init__(self, parent)
        self.statusbar = statusbar
        self.parent = parent

        self.list = FastObjectListView(self,
                                       sortable=True,
                                       style=wx.LC_REPORT | wx.SUNKEN_BORDER,
                                       size=(950, 350))
        self.list.handleStandardKeys = False
        self.list.SetEmptyListMsg("This database has no rows")
        self.list.SetEmptyListMsgFont(
            wx.FFont(24, wx.DEFAULT, faceName="Tekton"))

        self.width_date = 170
        self.width = 100
        self.width_model = 130
        self.check_date = 0

        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected, self.list)
        self.Bind(wx.EVT_LIST_COL_CLICK, self.OnItemSelected, self.list)

        mastersizer = wx.BoxSizer(wx.HORIZONTAL)
        mastersizer.Add(self.list, 0, wx.ALL, 5)

        pub.subscribe(self.fill_list, pubsub_fill_list_DB)
        pub.subscribe(self.re_fill_list, pubsub_update_db_nb_line)

        self.SetSizer(mastersizer)
        self.Layout()
        self.SetAutoLayout(1)
        self.SetupScrolling()
        self.initialize_list()
        c = DataBaseUse()
        c.initialize_database()

    def initialize_list(self):
        temp = []
        ic_ = prog_icon_curve.GetBitmap()
        ImageIndex = self.list.AddImages(ic_)
        self.list.AddNamedImages("date", ic_)
        for i in range(len(headercolumnname) - 1):
            if i == 0:
                temp.append(
                    ColumnDefn(headercolumnname[i],
                               "center",
                               self.width_date,
                               valueGetter=databasename[0],
                               imageGetter=ImageIndex,
                               maximumWidth=self.width_date))
            else:
                temp.append(
                    ColumnDefn(headercolumnname[i],
                               "center",
                               self.width,
                               valueGetter=databasename[i],
                               maximumWidth=self.width))
        i += 1
        temp.append(
            ColumnDefn(headercolumnname[i],
                       "center",
                       self.width_model,
                       valueGetter=databasename[i],
                       maximumWidth=self.width_model))
        self.list.SetColumns(temp)

    def fill_list(self, case, l):
        a = P4Rm()
        self.Freeze()
        if case == 0:
            self.list.SetObjects(l)
        elif case == 1:
            self.list.AddObject(l)
            pub.sendMessage(pubsub_refill_list_name_DB)
            pub.sendMessage(pubsub_search_combobox_DB)
        objects = self.list.GetObjects()
        self.list.SortBy(0, ascending=False)
        if a.db_nb_line is not -1:
            self.list.SetFilter(Filter.Head(a.db_nb_line))
            self.list.RepopulateList()
        else:
            self.list.SetFilter(None)
        self.list.RefreshObjects(objects)
        self.Thaw()
Example #2
0
class MyFrame(wx.Frame):

    DB_PATH = "" # Give this a full path if you want to look at an existing database

    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, **kwds)
        self.tableName = ""
        self.primaryKey = ""

        self.InitWidgets()
        self.InitDb()
        self.UpdateListEditability()


    def InitDb(self):
        path = self.DB_PATH or os.path.join(wx.StandardPaths.Get().GetTempDir(), "SqlExample.sqlite")
        if os.path.exists(path):
            self.connection = sqlite.connect(path)
        else:
            self.connection = self.CreateDb(path)


    def CreateDb(self, path):
        CREATE_STMT = "CREATE TABLE tracks (trackId int, title text, artist text, album text, sizeInBytes int, rating int, PRIMARY KEY (trackId))"
        INSERT_STMT = "INSERT INTO tracks VALUES(?, ?, ?, ?, ?, ?)"
        NUMBER_OF_ROWS = 10000

        connection = sqlite.connect(path)
        connection.execute(CREATE_STMT)
        connection.commit()

        start = time.clock()
        i = 0
        while i < NUMBER_OF_ROWS:
            for x in ExampleModel.GetTracks():
                connection.execute(INSERT_STMT, [i, x.title + str(i), x.artist, x.album, x.sizeInBytes, x.rating])
                i += 1
        connection.commit()
        #print "Building database of %d rows took %2f seconds." % (NUMBER_OF_ROWS, time.clock() - start)

        return connection


    def InitWidgets(self):
        panel = wx.Panel(self, -1)
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(panel, 1, wx.ALL|wx.EXPAND)
        self.SetSizer(sizer_1)

        self.tcSql = wx.TextCtrl(panel, -1, "select trackId, title, artist, album, sizeInBytes, rating from tracks;", style=wx.TE_MULTILINE|wx.TE_PROCESS_ENTER)
        self.myOlv = FastObjectListView(panel, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)
        self.stMsg = wx.StaticText(panel, -1, "Default value")
        sizer_2 = wx.FlexGridSizer(3, 1, 0, 0)
        sizer_2.Add(self.tcSql, 1, wx.ALL|wx.EXPAND, 4)
        sizer_2.Add(self.myOlv, 1, wx.ALL|wx.EXPAND, 4)
        sizer_2.Add(self.stMsg, 1, wx.ALL|wx.EXPAND, 4)
        sizer_2.AddGrowableCol(0)
        sizer_2.AddGrowableRow(1)

        panel.SetSizer(sizer_2)

        self.Bind(wx.EVT_TEXT_ENTER, self.HandleTextEnter, self.tcSql)
        self.myOlv.Bind(EVT_CELL_EDIT_STARTING, self.HandleCellEditStarting)
        self.myOlv.Bind(EVT_CELL_EDIT_FINISHED, self.HandleCellEditFinished)

        self.Layout()

    #----------------------------------------------------------------------------
    # Event handling

    def HandleTextEnter(self, evt):
        self.tableName = ""
        self.primaryKey = ""
        try:
            self.myOlv.SetEmptyListMsg("Executing statement...")
            self.DoSelect(self.tcSql.GetValue())
            self.CalculatePrimaryKey(self.tcSql.GetValue())
        except sqlite.Error, e:
            self.myOlv.SetEmptyListMsg("Error: %s" % e.args[0])
        self.UpdateListEditability()
Example #3
0
class pnlDataTable(wx.Panel):

    # selectedpoints = []
    def _init_ctrls(self, prnt):
        # generated method, don't edit
        wx.Panel.__init__(self,
                          id=wxID_PNLDATATABLE,
                          name=u'pnlDataTable',
                          parent=prnt,
                          size=wx.Size(677, 449),
                          style=wx.TAB_TRAVERSAL)
        self.myOlv = FastObjectListView(self, -1, style=wx.LC_REPORT)  #Virtual

        # self.myOlv.SetObjectGetter(self.fetchFromDatabase)
        self.myOlv.SetEmptyListMsg("")

        sizer_2 = wx.BoxSizer(wx.VERTICAL)
        sizer_2.Add(self.myOlv, 1, wx.ALL | wx.EXPAND, 4)
        self.SetSizer(sizer_2)
        self.doneselecting = True

        self.myOlv._highlightBrush = wx.Brush("red")
        self.myOlv.Bind(wx.EVT_LIST_ITEM_SELECTED, self.OnItemSelected)
        ##        self.myOlv.Bind(wx.EVT_LIST_COL_END_DRAG , self.OnLUp,id=wxID_PNLDATATABLE )
        ##        self.myOlv.Bind(wx.EVT_LIST_ITEM_DESELECTED, self.OnItemDeSelected )
        ##        self.myOlv.Bind(wx.EVT_LEFT_UP, self.OnLUp, id=wxID_PNLDATATABLE )
        ##        self.myOlv.Bind(wx.EVT_LEFT_DOWN, self.OnLDown, id=wxID_PNLDATATABLE)
        Publisher.subscribe(self.OnChangeSelection, ("changeTableSelection"))
        Publisher.subscribe(self.OnRefresh, ("refreshTable"))

        self.Layout()

    # def Init(self, DVConn):
    #     self.cursor = DVConn
    #     sql = "SELECT * FROM DataValuesEdit"
    #     self.cursor.execute(sql)

    #     self.myOlv.SetColumns( ColumnDefn(x[0], valueGetter=i, minimumWidth=40) for (i,x) in enumerate(self.cursor.description))

    #     #####table Settings
    #     self.myOlv.useAlternateBackColors = True
    #     self.myOlv.oddRowsBackColor = "SlateGray"
    #     self.myOlv.AutoSizeColumns()

    #     self.values = [list(x) for x in self.cursor.fetchall()]
    #     self.myOlv.SetObjects(self.values)

    def Init(self, dataRep, record_service):
        self.dataRep = dataRep
        self.record_service = record_service

        self.myOlv.SetColumns(
            ColumnDefn(x, valueGetter=i, minimumWidth=40)
            for x, i in self.dataRep.getEditColumns())

        #####table Settings
        self.myOlv.useAlternateBackColors = True
        self.myOlv.oddRowsBackColor = "SlateGray"
        self.myOlv.AutoSizeColumns()

        # self.values = [list(x) for x in self.cursor.fetchall()]
        self.myOlv.SetObjects(self.dataRep.getDataValuesforEdit())

    def OnRefresh(self, e):
        self.myOlv.SetObjects(self.dataRep.getDataValuesforEdit())

    def Clear(self):
        self.dataRep = None
        self.record_service = None
        self.myOlv.SetObjects(None)

    def OnLUp(self, event):
        print "in up"
        self.doneselecting = True

    def OnLDown(self, event):
        print "in down"
        self.doneselecting = False

    def OnItemSelected(self, event):
        # print "in onItemSelected"

        # if  not (event.m_itemIndex in self.selectedpoints):
        #     self.selectedpoints.Add(event.m_itemIndex)

        if self.doneselecting:
            selectedids = self.getSelectedIDs(self.myOlv.GetSelectedObjects())
            Publisher.sendMessage(("changePlotSelection"), sellist=selectedids)

    def OnItemDeSelected(self, event):
        print event.m_itemIndex
        # self.selectedpoints.remove(event.m_itemIndex)

    def getSelectedIDs(self, selobjects):
        idlist = [False] * self.dataRep.getEditRowCount()
        for sel in selobjects:
            idlist[self.myOlv.GetIndexOf(sel)] = True
        # print idlist
        return idlist

    def OnChangeSelection(self, sellist):
        objlist = []
        # print sellist
        # print type(sellist)

        for i in range(len(sellist)):
            if sellist[i]:
                objlist.append(self.myOlv.GetObjectAt(i))
        # print objlist
        self.doneselecting = False
        self.myOlv.SelectObjects(objlist, deselectOthers=True)
        self.doneselecting = True
        self.myOlv.SetFocus()

    def stopEdit(self):
        self.Clear()

# a) Call self.list_ctrl.SetFocus() right after you click the button;
# b) Change the self._highlightUnfocusedBrush and self._highlightBrush
# colours in the ULC source code to always return the brush colours you
# want (not recommended).

#########self.myOlv.GetCheckedObjects
#########IsChecked(ModelObject)
########Uncheck(modelObject), Check(modelObject)

    def __init__(self, parent, id, size, style, name, pos=None):
        self._init_ctrls(parent)
Example #4
0
class MainPanel(wx.Panel):
    """Main Panel of the application"""

    # ----------------------------------------------------------------------
    def __init__(self, parent, theme):
        """
        Constructor
        Defines the ObjectListView for dropped items
        and the layout for its components
        """
        wx.Panel.__init__(self, parent=parent)
        self.videos_list = []

        self.primary_background_color = theme.get("primaryBackgroundColor")
        self.secondary_background_color = theme.get("secondaryBackgroundColor")
        self.foreground_color = theme.get("foregroundColor")
        self.list_font = wx.Font(pointSize=11,
                                 family=wx.FONTFAMILY_SWISS,
                                 style=wx.FONTSTYLE_NORMAL,
                                 weight=wx.FONTWEIGHT_LIGHT,
                                 underline=False,
                                 faceName='Roboto')
        self.regular_font = wx.Font(pointSize=12,
                                    family=wx.FONTFAMILY_SWISS,
                                    style=wx.FONTSTYLE_NORMAL,
                                    weight=wx.FONTWEIGHT_NORMAL,
                                    underline=False,
                                    faceName='Roboto')
        self.big_font = wx.Font(pointSize=32,
                                family=wx.FONTFAMILY_SWISS,
                                style=wx.FONTSTYLE_NORMAL,
                                weight=wx.FONTWEIGHT_BOLD,
                                underline=False,
                                faceName='Roboto')

        self.SetBackgroundColour(self.primary_background_color)
        self.SetForegroundColour(self.foreground_color)

        video_drop_target = VideoDropTarget(self)
        self.olv = FastObjectListView(self,
                                      style=wx.LC_REPORT | wx.BORDER_NONE)
        self.olv.SetEmptyListMsg(i18n.t('i18n.emptyList'))
        self.olv.SetDropTarget(video_drop_target)
        self.olv.cellEditMode = FastObjectListView.CELLEDIT_NONE
        self.olv.SetEmptyListMsgFont(self.big_font)
        self.olv.SetFont(self.list_font)
        self.set_files()

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.olv.Bind(wx.EVT_KEY_UP, self.on_delete)
        self.sizer.Add(self.olv, 1, wx.EXPAND)

        grid1 = wx.GridSizer(1, 3, 1, 10)
        grid2 = wx.GridSizer(1, 3, 1, 10)

        self.lbl_cut_init = wx.StaticText(self, -1,
                                          i18n.t('i18n.lblCutInitSec'))
        self.lbl_cut_init.SetFont(self.regular_font)

        self.txt_cut_init = wx.TextCtrl(self,
                                        -1,
                                        "0",
                                        size=(175, -1),
                                        style=wx.BORDER_STATIC)
        self.txt_cut_init.SetBackgroundColour(self.secondary_background_color)
        self.txt_cut_init.SetForegroundColour(self.foreground_color)
        self.txt_cut_init.SetFont(self.regular_font)

        self.lbl_cut_end = wx.StaticText(self, -1, i18n.t('i18n.lblCutEndSec'))
        self.lbl_cut_end.SetFont(self.regular_font)

        self.txt_cut_end = wx.TextCtrl(self,
                                       -1,
                                       "0",
                                       size=(175, -1),
                                       style=wx.BORDER_STATIC)
        self.txt_cut_end.SetBackgroundColour(self.secondary_background_color)
        self.txt_cut_end.SetForegroundColour(self.foreground_color)
        self.txt_cut_end.SetFont(self.regular_font)

        self.chk_delete = wx.CheckBox(self, -1, i18n.t('i18n.chkDelete'))
        self.chk_delete.SetFont(self.regular_font)

        grid1.AddMany([self.lbl_cut_init, self.lbl_cut_end])
        grid1.AddSpacer(0)
        grid2.AddMany([self.txt_cut_init, self.txt_cut_end, self.chk_delete])

        self.btn_cut = wx.Button(self,
                                 -1,
                                 i18n.t('i18n.btnCut'),
                                 size=(100, 50),
                                 style=wx.BORDER_NONE)
        self.btn_cut.Bind(wx.EVT_BUTTON, self.on_cut)
        self.btn_cut.SetBackgroundColour(self.secondary_background_color)
        self.btn_cut.SetForegroundColour(self.foreground_color)
        self.btn_cut.SetFont(self.big_font)

        self.sizer.AddSpacer(20)
        self.sizer.Add(grid1, 0, wx.EXPAND | wx.LEFT | wx.BOTTOM, 10)
        self.sizer.Add(grid2, 0, wx.EXPAND | wx.LEFT, 10)
        self.sizer.AddSpacer(20)
        self.sizer.Add(self.btn_cut, 0, wx.EXPAND)
        self.SetSizer(self.sizer)

    # ----------------------------------------------------------------------
    def update_display(self, videos_list):
        """
        Triggered when dropped items,
        get the item and transform it into VideoInfo with parameters
        to use it in ObjectListView
        """
        import nmi_video
        for path in videos_list:
            file_stats = os.stat(path)
            try:
                clip_duration = nmi_video.get_video_duration(path)
            except Exception as e:
                dialog = wx.RichMessageDialog(self,
                                              i18n.t('i18n.onlyVideosError'),
                                              "Error", wx.ICON_ERROR)
                dialog.ShowDetailedText("Error info:\n" + "\\" + str(e) + "\\")
                dialog.ShowModal()
                return
            minutes_lenght = str(datetime.timedelta(seconds=clip_duration))
            file_size = file_stats[stat.ST_SIZE]
            if (file_size > 1024):
                file_size = file_size / 1024.0
                if (file_size > 1024.0):
                    file_size = file_size / 1024.0
                    file_size = "%.2f MB" % file_size
                else:
                    file_size = "%.2f KB" % file_size

            self.videos_list.append(
                nmi_video.VideoInfo(path, minutes_lenght, file_size))

        self.olv.SetObjects(self.videos_list)

    # ----------------------------------------------------------------------
    def set_files(self):
        """Set the columns for items dropped"""
        self.olv.SetColumns([
            ColumnDefn(i18n.t('i18n.colName'),
                       "left",
                       250,
                       "name",
                       isSpaceFilling=True),
            ColumnDefn(i18n.t('i18n.colMinutes'), "right", 150,
                       "minutes_lenght"),
            ColumnDefn(i18n.t('i18n.colSize'), "right", 150, "size")
        ])
        self.olv.SetObjects(self.videos_list)

    # ----------------------------------------------------------------------
    def on_cut(self, event):
        """
        Trigger when click on CUT Button,
        Get parameters and in a for loop cut videos calling the function
        """
        import nmi_video
        try:
            beginning = int(self.txt_cut_init.GetLineText(1))
            end = int(self.txt_cut_end.GetLineText(1))
            delete = self.chk_delete.GetValue()
            delete_videos_list = list()
        except Exception as e:
            dialog = wx.RichMessageDialog(self, i18n.t('i18n.onlyNumberError'),
                                          "Error", wx.ICON_ERROR)
            dialog.ShowDetailedText("Error info:\n" + "\\" + str(e) + "\\")
            dialog.ShowModal()
            return

        if (len(self.videos_list) > 0):
            c = 0
            list_count = len(self.videos_list)
            dialog = wx.ProgressDialog(
                i18n.t('i18n.cutProgressTitle'),
                i18n.t('i18n.cutProgress') + str(c) + '/' + str(list_count),
                maximum=list_count,
                style=wx.PD_SMOOTH | wx.PD_CAN_ABORT | wx.PD_AUTO_HIDE)
            for file in self.videos_list:
                cut = nmi_video.cut_video(beginning, end, file)
                if (cut.get('state') is True):
                    delete_videos_list.append(file)
                    c += 1
                    if (dialog.WasCancelled() is True):
                        dialog = wx.RichMessageDialog(self,
                                                      i18n.t('i18n.cutCancel'),
                                                      "Error", wx.ICON_ERROR)
                        dialog.ShowModal()
                        break
                    dialog.Update(
                        c,
                        i18n.t('i18n.cutProgress') + str(c + 1) + '/' +
                        str(list_count))
            for file in delete_videos_list:
                self.videos_list.remove(file)
            self.olv.RemoveObjects(delete_videos_list)
            self.olv.SetObjects(self.videos_list)
            wx.MessageBox(
                str(c) + i18n.t('i18n.cutVideos'), "OK", wx.ICON_INFORMATION)
        else:
            dialog = wx.RichMessageDialog(self,
                                          i18n.t('i18n.noCutVideosError'),
                                          "Error", wx.ICON_ERROR)
            dialog.ShowModal()
            return

        if (delete is True):
            try:
                nmi_video.delete_videos(delete_videos_list)
                wx.MessageBox(i18n.t('i18n.deletedOld'), "OK",
                              wx.ICON_INFORMATION)
            except Exception as e:
                dialog = wx.RichMessageDialog(self,
                                              i18n.t('i18n.permisionError'),
                                              "Error", wx.ICON_ERROR)
                dialog.ShowDetailedText("Error info:\n" + "\\" + str(e) + "\\")
                dialog.ShowModal()

    # ----------------------------------------------------------------------
    def on_delete(self, event):
        """Trigger the event when user delete item from list with SUPR"""
        if (event.GetUnicodeKey() == 127
                and self.olv.GetSelectedItemCount() > 0):
            for i in self.olv.GetSelectedObjects():
                self.videos_list.remove(i)
            self.olv.RemoveObjects(self.olv.GetSelectedObjects())
            self.olv.SetObjects(self.videos_list)