def setupUI(self):
        self.mainHBoxLayout = QtGui.QHBoxLayout()
        self.mainRVBoxLayout = QtGui.QVBoxLayout()
        self.mainLVBoxLayout = QtGui.QVBoxLayout()
        self.executeCrawler = QtGui.QPushButton("Get Content!!!")
        self.urlBarLineEdit = QtGui.QLineEdit(
            "http://www2.tpa.edu.tw/tpaedu/Home/login.asp")
        self.myWebView = WebView()
        self.myTabWidget = TabWidget()

        #self.myWebView.settings().setDefaultTextEncoding("big5")
        self.myWebView.show()
        self.myTabWidget.addTab(self.myWebView, "my Web View")

        self.mainLVBoxLayout.addWidget(self.urlBarLineEdit)
        self.mainLVBoxLayout.addWidget(self.myTabWidget)
        self.mainRVBoxLayout.addWidget(self.executeCrawler)

        self.mainHBoxLayout.addLayout(self.mainLVBoxLayout)
        self.mainHBoxLayout.addLayout(self.mainRVBoxLayout)
        self.setLayout(self.mainHBoxLayout)

        self.executeCrawler.clicked.connect(self.slotClickedToLoadUrl)
        self.signalClickedToLoadUrl.connect(self.slotLoadUrl)
        self.myWebView.loadFinished.connect(self.slotWebViewLoadFinished)

        self.show()
 def __init__(self):
     super(Server, self).__init__()
     self.widget = TabWidget()
     self.monitor = MoniterThread()
     self.widget.closeSignal.connect(self.stopServer)
     self.newConnection.connect(self.newConnectionHandler)
     self.addNewThread.connect(self.monitor.addNewThread)
     pass
	def setupUI(self) :
		self.mainHBoxLayout = QtGui.QHBoxLayout()
		self.mainRVBoxLayout = QtGui.QVBoxLayout()
		self.mainLVBoxLayout = QtGui.QVBoxLayout()
		self.executeCrawler = QtGui.QPushButton("Get Content!!!")
		self.urlBarLineEdit = QtGui.QLineEdit("http://www2.tpa.edu.tw/tpaedu/Home/login.asp")
		self.myWebView = WebView()
		self.myTabWidget = TabWidget()
		
		#self.myWebView.settings().setDefaultTextEncoding("big5")
		self.myWebView.show()
		self.myTabWidget.addTab(self.myWebView, "my Web View")
		
		self.mainLVBoxLayout.addWidget(self.urlBarLineEdit)
		self.mainLVBoxLayout.addWidget(self.myTabWidget)
		self.mainRVBoxLayout.addWidget(self.executeCrawler)
		
		self.mainHBoxLayout.addLayout(self.mainLVBoxLayout)
		self.mainHBoxLayout.addLayout(self.mainRVBoxLayout)
		self.setLayout(self.mainHBoxLayout)
		
		self.executeCrawler.clicked.connect(self.slotClickedToLoadUrl)
		self.signalClickedToLoadUrl.connect(self.slotLoadUrl)
		self.myWebView.loadFinished.connect(self.slotWebViewLoadFinished)
		
		self.show()
	def __init__(self) :
		super(Server, self).__init__()
		self.widget = TabWidget()
		self.monitor = MoniterThread()
		self.widget.closeSignal.connect(self.stopServer)
		self.newConnection.connect(self.newConnectionHandler)
		self.addNewThread.connect(self.monitor.addNewThread)
		pass
class Server(QtNetwork.QTcpServer) :
	addNewThread = QtCore.Signal(MoniterObject)
	
	# basic initial 
	# private object :
	# 	widget : TabWidget for WebView
	#	monitor : A thread object for monite all connection and release finished connection
	# connections :
	#	when main widget close, it will shutdown server instantly
	#	a new connection handler
	#	monitor add new object event
	def __init__(self) :
		super(Server, self).__init__()
		self.widget = TabWidget()
		self.monitor = MoniterThread()
		self.widget.closeSignal.connect(self.stopServer)
		self.newConnection.connect(self.newConnectionHandler)
		self.addNewThread.connect(self.monitor.addNewThread)
		pass
	
	# start monitor, show widget, start service
	def run(self) :
		self.monitor.start()
		self.widget.show()
		self.listen(QtNetwork.QHostAddress("127.0.0.1"), 5000)
		
	@QtCore.Slot()
	def newConnectionHandler(self) :
		newTcpSocket = self.nextPendingConnection() # get new connection socket
		connection = Connection(newTcpSocket) # create a new connection delegate object
		crossThread = CrossThread() # create connection thread
		self.widget.addTab(str(crossThread.currentThreadId()), connection.widget()) # insert connection attach widget to server main widget
		connection.closeConnection.connect(self.widget.deleteTab) # connect connection close to remove widget of server main widget
		crossThread.finishedSignal.connect(self.monitor.deleteThread) # when a thread dead or finish its job, it will tell monitor to delete it.
		crossThread.startedSignal.connect(connection.service) # inform new connection thread start service.
		connection.moveToThread(crossThread) # let connection run in new thread 
		moniterObject = MoniterObject(crossThread, connection) # create a monitor object for monitor thread
		self.addNewThread.emit(moniterObject) # make monitor thread registe a new monitor object
		crossThread.start() # new connection thread start running
	
	# don't stop directly, it will wait all thread finished and stop safely
	@QtCore.Slot()
	def stopServer(self) :
		self.monitor.deleteAll()
		
		while not self.monitor.isFinished() :
			pass
			
		print("Is monitor thread is end ? : " + str(self.monitor.isFinished()))
		
		self.close()
		self.widget.deleteLater()
		self.deleteLater()
Beispiel #6
0
 def setupUI(self):
    self.tabLayout = QVBoxLayout(self)
    self.tabs = TabWidget()
    self.tabLayout.addWidget(self.tabs)
    self.mainMenuTab = self.tabs.createTab('Main Menu')
    self.mainMenuLayout = QVBoxLayout(self.mainMenuTab)
    
    self.mainMenu = MenuWidget()
    self.mainMenu.selected.connect(self.mainMenuSelected)
    self.mainMenu.exit.connect(self.close)
    self.mainMenu.add(SimpleMenuItem('Live TV'))
    self.mainMenu.add(SimpleMenuItem('Watch Recordings'))
    self.mainMenu.add(SimpleMenuItem('Settings'))
    self.mainMenuLayout.addWidget(self.mainMenu)
    
    self.createRecordingsTab()
    self.createSettingsTab()
    
    self.messageDialog = MessageDialog(self)
    def __init__(self, parent=None):
        self.wMutex = Lock()
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle("&Linux Download Manager")
        p = QtGui.QPixmap(os.getcwd() + "/image/close.png")

        self.goTerminate = 0

        self.PARTS = 10
        self.timer = QtCore.QTimer()
        self.links = 0
        self.trayIcon = QtGui.QSystemTrayIcon(self)

        self.dLocation = "/home"
        loc = ""
        if os.path.exists(os.getcwd() + "/Locale/desF"):
            f = open(os.getcwd() + "/Locale/desF", "r")
            loc = f.read()
            f.close()
        if len(loc) > 0:
            if os.path.exists(loc):
                self.dLocation = loc

        self.dLoads = {}
        self.posMove = None
        self.setMouseTracking(1)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        ldmLbl = QtGui.QLabel(self)

        cBox = QtGui.QComboBox(self)
        cBox.setToolTip("Fuzzy Partitioning")
        cBox.addItem("Partition")
        cBox.addItem("No Part 1")
        cBox.addItem("Few 5")
        cBox.addItem("Some 10")
        cBox.addItem("More 15")
        cBox.addItem("SuperSonic 20")

        cBox.setFrame(True)

        self.menuBtn = QtGui.QPushButton(self)
        minimize = QtGui.QPushButton(self)
        close = QtGui.QPushButton(self)
        YDldr = QtGui.QPushButton(self)
        ODldr = QtGui.QPushButton(self)
        Grbr = QtGui.QPushButton(self)
        credit = QtGui.QPushButton(self)

        self.pref = NetworkProxy(None, os.getcwd(), "&LDM")
        self.tabWidget = TabWidget(self.wMutex, self)

        self.createMenu()
        self.addTrayIcon()

        credit.setText("Credit")
        ldmLbl.setText("& Linux Download Manager")

        YDldr.setStyleSheet("background-image:url(" + os.getcwd() + "/image/Ytdlr.png);border-width:2px;")
        ODldr.setStyleSheet("background-image:url(" + os.getcwd() + "/image/ODld.png);border-width:2px;")
        Grbr.setStyleSheet("background-image:url(" + os.getcwd() + "/image/Grabber.png);border-width:2px;")
        ldmLbl.setStyleSheet("font-size:25px;font-family:lucida calligraphy;color:grey;")
        minimize.setStyleSheet("background-image:url(" + os.getcwd() + "/image/minimize.png);border-width:2px;")
        close.setStyleSheet("background-image:url(" + os.getcwd() + "/image/close.png);border-width:2px;")

        ldmLbl.setGeometry(250, 10, 400, 30)
        self.menuBtn.setGeometry(20, 20, 30, 20)
        cBox.setGeometry(10, 45, 100, 20)
        minimize.setGeometry(675, 0, 35, 22)
        close.setGeometry(710, 0, 35, 22)
        YDldr.setGeometry(10, 70, 100, 90)
        ODldr.setGeometry(10, 160, 100, 90)
        Grbr.setGeometry(10, 250, 100, 90)
        credit.setGeometry(10, 360, 100, 30)

        self.tabWidget.setGeometry(120, 40, 620, 350)

        self.resize(760, 400)
        self.trayIcon.show()

        self.connect(cBox, QtCore.SIGNAL("activated(int)"), self.sayIndex)
        self.connect(close, QtCore.SIGNAL("clicked()"), self.goToTray)
        self.connect(credit, QtCore.SIGNAL("clicked()"), self.creditMsg)
        self.connect(minimize, QtCore.SIGNAL("clicked()"), self.showMinimized)
        self.connect(Grbr, QtCore.SIGNAL("clicked()"), self.runSiteGrabber)
        self.connect(YDldr, QtCore.SIGNAL("clicked()"), self.YoutubeLinkDownload)
        self.connect(ODldr, QtCore.SIGNAL("clicked()"), self.fetchAndSaveUrl)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.regulateDownload)
        self.timer.start(2000)
class MainFrame(QtGui.QWidget):
    def __init__(self, parent=None):
        self.wMutex = Lock()
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle("&Linux Download Manager")
        p = QtGui.QPixmap(os.getcwd() + "/image/close.png")

        self.goTerminate = 0

        self.PARTS = 10
        self.timer = QtCore.QTimer()
        self.links = 0
        self.trayIcon = QtGui.QSystemTrayIcon(self)

        self.dLocation = "/home"
        loc = ""
        if os.path.exists(os.getcwd() + "/Locale/desF"):
            f = open(os.getcwd() + "/Locale/desF", "r")
            loc = f.read()
            f.close()
        if len(loc) > 0:
            if os.path.exists(loc):
                self.dLocation = loc

        self.dLoads = {}
        self.posMove = None
        self.setMouseTracking(1)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        ldmLbl = QtGui.QLabel(self)

        cBox = QtGui.QComboBox(self)
        cBox.setToolTip("Fuzzy Partitioning")
        cBox.addItem("Partition")
        cBox.addItem("No Part 1")
        cBox.addItem("Few 5")
        cBox.addItem("Some 10")
        cBox.addItem("More 15")
        cBox.addItem("SuperSonic 20")

        cBox.setFrame(True)

        self.menuBtn = QtGui.QPushButton(self)
        minimize = QtGui.QPushButton(self)
        close = QtGui.QPushButton(self)
        YDldr = QtGui.QPushButton(self)
        ODldr = QtGui.QPushButton(self)
        Grbr = QtGui.QPushButton(self)
        credit = QtGui.QPushButton(self)

        self.pref = NetworkProxy(None, os.getcwd(), "&LDM")
        self.tabWidget = TabWidget(self.wMutex, self)

        self.createMenu()
        self.addTrayIcon()

        credit.setText("Credit")
        ldmLbl.setText("& Linux Download Manager")

        YDldr.setStyleSheet("background-image:url(" + os.getcwd() + "/image/Ytdlr.png);border-width:2px;")
        ODldr.setStyleSheet("background-image:url(" + os.getcwd() + "/image/ODld.png);border-width:2px;")
        Grbr.setStyleSheet("background-image:url(" + os.getcwd() + "/image/Grabber.png);border-width:2px;")
        ldmLbl.setStyleSheet("font-size:25px;font-family:lucida calligraphy;color:grey;")
        minimize.setStyleSheet("background-image:url(" + os.getcwd() + "/image/minimize.png);border-width:2px;")
        close.setStyleSheet("background-image:url(" + os.getcwd() + "/image/close.png);border-width:2px;")

        ldmLbl.setGeometry(250, 10, 400, 30)
        self.menuBtn.setGeometry(20, 20, 30, 20)
        cBox.setGeometry(10, 45, 100, 20)
        minimize.setGeometry(675, 0, 35, 22)
        close.setGeometry(710, 0, 35, 22)
        YDldr.setGeometry(10, 70, 100, 90)
        ODldr.setGeometry(10, 160, 100, 90)
        Grbr.setGeometry(10, 250, 100, 90)
        credit.setGeometry(10, 360, 100, 30)

        self.tabWidget.setGeometry(120, 40, 620, 350)

        self.resize(760, 400)
        self.trayIcon.show()

        self.connect(cBox, QtCore.SIGNAL("activated(int)"), self.sayIndex)
        self.connect(close, QtCore.SIGNAL("clicked()"), self.goToTray)
        self.connect(credit, QtCore.SIGNAL("clicked()"), self.creditMsg)
        self.connect(minimize, QtCore.SIGNAL("clicked()"), self.showMinimized)
        self.connect(Grbr, QtCore.SIGNAL("clicked()"), self.runSiteGrabber)
        self.connect(YDldr, QtCore.SIGNAL("clicked()"), self.YoutubeLinkDownload)
        self.connect(ODldr, QtCore.SIGNAL("clicked()"), self.fetchAndSaveUrl)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.regulateDownload)
        self.timer.start(2000)

    def sayIndex(self, index):
        if index == 1:
            self.PARTS = 1
        elif not (index == 0):
            self.PARTS = 5 * (index - 1)

    def runingWin(self, index):
        if not (self.dLoads[index] == None):
            self.dLoads[index].flag = self.dLoads[index].flag | 0x0010

    def regulateDownload(self):
        for key in self.dLoads:
            flag = self.dLoads[key].flag
            if not (self.dLoads[key].free):
                self.tabWidget.updateEntry(
                    self.dLoads[key].getInfo(), self.dLoads[key].downloaded, self.dLoads[key].timeLeft
                )
            if flag & 0x0002:
                self.dLoads[key].free = 0
                self.dLoads[key].flag = flag & 0xFFFD
                self.dLoads[key].free = 1
                self.dLoads[key].obj.hide()
                self.downloads.delAction(key)
                self.tabWidget.updateEntry(self.dLoads[key].getInfo(), self.dLoads[key].downloaded, "0", 1)
            if flag & 0x0008:
                self.dLoads[key].obj.show()
                self.downloads.pushAction(key, self.dLoads[key].fileName, self)
                self.dLoads[key].flag = flag & 0xFFF7
                self.tabWidget.makeEntry(self.dLoads[key].getInfo())
            if flag & 0x0100:
                self.downloads.pushAction(key, self.dLoads[key].fileName, self)
                self.dLoads[key].obj.show()
                self.dLoads[key].flag = flag & 0xFEFF

            if flag & 0x0004:
                self.dLoads[key].free = 0
                self.dLoads[key].obj.hide()
                self.dLoads[key].flags = flag & 0xFFFB
                self.dLoads[key].free = 1
                self.downloads.delAction(key)
                self.tabWidget.updateEntry(self.dLoads[key].getInfo(), int(self.dLoads[key].length), "0", 1)
                self.dLoads[key].flag = flag & 0xFFFB

            if flag & 0x0040:
                self.dLoads[key].free = 1
                self.dLoads[key].clear()
                self.downloads.delAction(key)
                ok = QtGui.QMessageBox(
                    QtGui.QMessageBox.Information,
                    "Oops",
                    "Fatal Error In Download",
                    QtGui.QMessageBox.Ok,
                    self,
                    QtCore.Qt.FramelessWindowHint,
                )
                ok.exec_()
                self.dLoads[key].flag = flag & 0xFFBF

        if self.goTerminate == 1:
            if self.freeKey() == -1:
                sys.exit(0)
        self.timer.start(2000)

    def runSiteGrabber(self):
        ok = QtGui.QMessageBox(
            QtGui.QMessageBox.Information,
            "Site Grabber",
            "Sorry This facility is currently unavilable .  You may contribute for it.",
            QtGui.QMessageBox.Ok,
            self,
            QtCore.Qt.FramelessWindowHint,
        )
        ok.show()

    def freeKey(self):
        for key in self.dLoads:
            if self.dLoads[key].free == 1:
                return key
        return -1

    def loadPartition(self, url):
        pass

    def YoutubeLinkDownload(self):
        txt, ok = QtGui.QInputDialog.getText(
            self, "YouTube Link", "YTube Link:", QtGui.QLineEdit.Normal, "", QtCore.Qt.FramelessWindowHint
        )
        if ok == True:
            if txt.startsWith("https://www.youtube.com"):
                key = self.freeKey()
                if key == -1:
                    obj = Interface(self.PARTS)
                else:
                    obj = self.dLoads[key]
                    obj.PARTS = self.PARTS
                    obj.clear()
                    del self.dLoads[key]

                thread.start_new_thread(obj.start_Download, (txt, self.wMutex))
                self.dLoads[self.links] = obj
                self.links = self.links + 1
            else:
                msg = QtGui.QMessageBox(
                    QtGui.QMessageBox.Warning,
                    "Oops.",
                    "Not a valid YTube Url ",
                    QtGui.QMessageBox.Ok,
                    self,
                    QtCore.Qt.FramelessWindowHint,
                )
                msg.show()

    def downloadPartition(self, url, fileName, dt, tm, length):
        key = self.freeKey()
        if key == -1:
            obj = Interface(self.PARTS)
            key = self.links
            self.links = self.links + 1
        else:
            obj = self.dLoads[key]
            obj.PARTS = self.PARTS
            obj.clear()
            del self.dLoads[key]
        obj.url = url
        obj.fileName = fileName
        obj.dt = dt
        obj.tm = tm
        obj.length = length
        bit = 0
        if url.startswith("http://www.youtube.com"):
            bit = 1
        thread.start_new_thread(obj.start_from_Part, (self.wMutex, bit))
        self.dLoads[key] = obj

    def fetchAndSaveUrl(self, url="", bit=1):
        ok = True
        if len(url) == 0:
            url, ok = QtGui.QInputDialog.getText(
                self, "Link", "Download Link:", QtGui.QLineEdit.Normal, "", QtCore.Qt.FramelessWindowHint
            )
        if ok == True:
            key = self.freeKey()
            if key == -1:
                obj = Interface(self.PARTS)
                key = self.links
                self.links = self.links + 1
            else:
                obj = self.dLoads[key]
                obj.PARTS = self.PARTS
                obj.clear()
                del self.dLoads[key]

            thread.start_new_thread(obj.start_Download, (url, self.wMutex, bit))
            self.dLoads[key] = obj
        else:
            msg = QtGui.QMessageBox(
                QtGui.QMessageBox.Warning,
                "Oops.",
                "Not a valid Url ",
                QtGui.QMessageBox.Ok,
                self,
                QtCore.Qt.FramelessWindowHint,
            )
            msg.show()

    def createMenu(self):
        menu = QtGui.QMenu(self)

        self.downloads = Menu("Downloads", self)
        miniToTray = QtGui.QAction("Minimize To Tray", self)
        setting = QtGui.QAction("Preference", self)
        cLoc = QtGui.QAction("Change Downloads Destination", self)
        quit = QtGui.QAction("Quit", self)

        miniToTray.setShortcut("Ctrl+M")
        menu.addMenu(self.downloads)
        menu.addSeparator()
        menu.addAction(miniToTray)
        menu.addAction(setting)
        menu.addSeparator()
        menu.addAction(cLoc)
        menu.addSeparator()
        menu.addAction(quit)

        self.menuBtn.setMenu(menu)
        self.connect(miniToTray, QtCore.SIGNAL("triggered()"), self.goToTray)
        self.connect(setting, QtCore.SIGNAL("triggered()"), self.getSetting)
        self.connect(cLoc, QtCore.SIGNAL("triggered()"), self.changeLoc)
        self.connect(quit, QtCore.SIGNAL("triggered()"), self.safeExit)

    def changeLoc(self):
        data = self.dLocation
        if not (os.path.exists(data)):
            data = "/home"
        fD = QtGui.QFileDialog(self, "Get Download Destination", data, "")
        fD.setOption(QtGui.QFileDialog.ShowDirsOnly, True)
        fD.setFileMode(2)
        fD.resize(500, 300)
        fLoc = ""
        if fD.exec_():
            if len(fD.selectedFiles()) > 0:
                fLoc = fD.selectedFiles()[0]
        fLoc = str(fLoc)
        if len(fLoc) > 0:
            if os.path.exists(fLoc):
                self.dLocation = fLoc
                f = open(os.getcwd() + "/Locale/desF", "w")
                f.write(fLoc)
                f.close()
                for key in self.dLoads:
                    if not (self.dLoads[key] == None):
                        self.dLoads[key].dLocation = fLoc

    def getSetting(self):
        self.pref.show()

    def addTrayIcon(self):
        self.trayIcon.setIcon(QtGui.QIcon("image/tray.png"))

        menu = QtGui.QMenu(self)
        showWin = QtGui.QAction("Show Window", self)
        quit = QtGui.QAction("Quit", self)

        menu.addAction(showWin)
        menu.addMenu(self.downloads)
        menu.addAction(quit)

        self.trayIcon.setContextMenu(menu)
        self.connect(showWin, QtCore.SIGNAL("triggered()"), self.getOutOfTray)
        self.connect(quit, QtCore.SIGNAL("triggered()"), self.safeExit)

    def mousePressEvent(self, event):
        self.posMove = event.pos()

    def mouseMoveEvent(self, event):
        if self.posMove:
            self.move(
                self.pos().x() + event.pos().x() - self.posMove.x(), self.pos().y() + event.pos().y() - self.posMove.y()
            )

    def mouseReleaseEvent(self, event):
        self.posMove = None

    def creditMsg(self):
        ok = QtGui.QMessageBox(
            QtGui.QMessageBox.Information,
            "LDM Community",
            "By using this application you are contributing to this development.Thanks a lot for it.\nHope you'll enjoy & share your experience\n-Anand Kumar\nEfficience\nSubscribe to  (linkinAnand.blogspot.com) to get all the latest information.\nDeveloper (twitter.com/EfficienceAnand)\ncurrently at IIITA",
            QtGui.QMessageBox.Ok,
            self,
            QtCore.Qt.FramelessWindowHint,
        )
        ok.show()

    def goToTray(self):
        if self.isVisible():
            self.hide()

    def getOutOfTray(self):
        if not (self.isVisible()):
            self.show()

    def safeExit(self):
        gT = True
        for key in self.dLoads:
            if self.dLoads[key].free == 0:
                gT = False
                break
        if gT == True:
            sys.exit(0)
        else:
            msg = QtGui.QMessageBox(
                QtGui.QMessageBox.Question,
                "!!",
                "Some Download process are still running\nWould you still like to quit the application ?",
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No,
                self,
                QtCore.Qt.FramelessWindowHint,
            )
            ok = msg.exec_()
            if ok == QtGui.QMessageBox.Yes:
                self.goTerminate = True
                for key in self.dLoads:
                    self.dLoads[key].flag | 0x0080
    def __init__(self, parent=None):
        self.wMutex = Lock()
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle('&Linux Download Manager')
        p = QtGui.QPixmap(os.getcwd() + '/image/close.png')

        self.goTerminate = 0

        self.PARTS = 10
        self.timer = QtCore.QTimer()
        self.links = 0
        self.trayIcon = QtGui.QSystemTrayIcon(self)

        self.dLocation = '/home'
        loc = ''
        if os.path.exists(os.getcwd() + '/Locale/desF'):
            f = open(os.getcwd() + '/Locale/desF', 'r')
            loc = f.read()
            f.close()
        if len(loc) > 0:
            if os.path.exists(loc):
                self.dLocation = loc

        self.dLoads = {}
        self.posMove = None
        self.setMouseTracking(1)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        ldmLbl = QtGui.QLabel(self)

        cBox = QtGui.QComboBox(self)
        cBox.setToolTip('Fuzzy Partitioning')
        cBox.addItem('Partition')
        cBox.addItem('No Part 1')
        cBox.addItem('Few 5')
        cBox.addItem('Some 10')
        cBox.addItem('More 15')
        cBox.addItem('SuperSonic 20')

        cBox.setFrame(True)

        self.menuBtn = QtGui.QPushButton(self)
        minimize = QtGui.QPushButton(self)
        close = QtGui.QPushButton(self)
        YDldr = QtGui.QPushButton(self)
        ODldr = QtGui.QPushButton(self)
        Grbr = QtGui.QPushButton(self)
        credit = QtGui.QPushButton(self)

        self.pref = NetworkProxy(None, os.getcwd(), '&LDM')
        self.tabWidget = TabWidget(self.wMutex, self)

        self.createMenu()
        self.addTrayIcon()

        credit.setText('Credit')
        ldmLbl.setText('& Linux Download Manager')

        YDldr.setStyleSheet('background-image:url(' + os.getcwd() +
                            '/image/Ytdlr.png);border-width:2px;')
        ODldr.setStyleSheet('background-image:url(' + os.getcwd() +
                            '/image/ODld.png);border-width:2px;')
        Grbr.setStyleSheet('background-image:url(' + os.getcwd() +
                           '/image/Grabber.png);border-width:2px;')
        ldmLbl.setStyleSheet(
            'font-size:25px;font-family:lucida calligraphy;color:grey;')
        minimize.setStyleSheet('background-image:url(' + os.getcwd() +
                               '/image/minimize.png);border-width:2px;')
        close.setStyleSheet('background-image:url(' + os.getcwd() +
                            '/image/close.png);border-width:2px;')

        ldmLbl.setGeometry(250, 10, 400, 30)
        self.menuBtn.setGeometry(20, 20, 30, 20)
        cBox.setGeometry(10, 45, 100, 20)
        minimize.setGeometry(675, 0, 35, 22)
        close.setGeometry(710, 0, 35, 22)
        YDldr.setGeometry(10, 70, 100, 90)
        ODldr.setGeometry(10, 160, 100, 90)
        Grbr.setGeometry(10, 250, 100, 90)
        credit.setGeometry(10, 360, 100, 30)

        self.tabWidget.setGeometry(120, 40, 620, 350)

        self.resize(760, 400)
        self.trayIcon.show()

        self.connect(cBox, QtCore.SIGNAL('activated(int)'), self.sayIndex)
        self.connect(close, QtCore.SIGNAL('clicked()'), self.goToTray)
        self.connect(credit, QtCore.SIGNAL('clicked()'), self.creditMsg)
        self.connect(minimize, QtCore.SIGNAL('clicked()'), self.showMinimized)
        self.connect(Grbr, QtCore.SIGNAL('clicked()'), self.runSiteGrabber)
        self.connect(YDldr, QtCore.SIGNAL('clicked()'),
                     self.YoutubeLinkDownload)
        self.connect(ODldr, QtCore.SIGNAL('clicked()'), self.fetchAndSaveUrl)
        self.connect(self.timer, QtCore.SIGNAL('timeout()'),
                     self.regulateDownload)
        self.timer.start(2000)
class MainFrame(QtGui.QWidget):
    def __init__(self, parent=None):
        self.wMutex = Lock()
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle('&Linux Download Manager')
        p = QtGui.QPixmap(os.getcwd() + '/image/close.png')

        self.goTerminate = 0

        self.PARTS = 10
        self.timer = QtCore.QTimer()
        self.links = 0
        self.trayIcon = QtGui.QSystemTrayIcon(self)

        self.dLocation = '/home'
        loc = ''
        if os.path.exists(os.getcwd() + '/Locale/desF'):
            f = open(os.getcwd() + '/Locale/desF', 'r')
            loc = f.read()
            f.close()
        if len(loc) > 0:
            if os.path.exists(loc):
                self.dLocation = loc

        self.dLoads = {}
        self.posMove = None
        self.setMouseTracking(1)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        ldmLbl = QtGui.QLabel(self)

        cBox = QtGui.QComboBox(self)
        cBox.setToolTip('Fuzzy Partitioning')
        cBox.addItem('Partition')
        cBox.addItem('No Part 1')
        cBox.addItem('Few 5')
        cBox.addItem('Some 10')
        cBox.addItem('More 15')
        cBox.addItem('SuperSonic 20')

        cBox.setFrame(True)

        self.menuBtn = QtGui.QPushButton(self)
        minimize = QtGui.QPushButton(self)
        close = QtGui.QPushButton(self)
        YDldr = QtGui.QPushButton(self)
        ODldr = QtGui.QPushButton(self)
        Grbr = QtGui.QPushButton(self)
        credit = QtGui.QPushButton(self)

        self.pref = NetworkProxy(None, os.getcwd(), '&LDM')
        self.tabWidget = TabWidget(self.wMutex, self)

        self.createMenu()
        self.addTrayIcon()

        credit.setText('Credit')
        ldmLbl.setText('& Linux Download Manager')

        YDldr.setStyleSheet('background-image:url(' + os.getcwd() +
                            '/image/Ytdlr.png);border-width:2px;')
        ODldr.setStyleSheet('background-image:url(' + os.getcwd() +
                            '/image/ODld.png);border-width:2px;')
        Grbr.setStyleSheet('background-image:url(' + os.getcwd() +
                           '/image/Grabber.png);border-width:2px;')
        ldmLbl.setStyleSheet(
            'font-size:25px;font-family:lucida calligraphy;color:grey;')
        minimize.setStyleSheet('background-image:url(' + os.getcwd() +
                               '/image/minimize.png);border-width:2px;')
        close.setStyleSheet('background-image:url(' + os.getcwd() +
                            '/image/close.png);border-width:2px;')

        ldmLbl.setGeometry(250, 10, 400, 30)
        self.menuBtn.setGeometry(20, 20, 30, 20)
        cBox.setGeometry(10, 45, 100, 20)
        minimize.setGeometry(675, 0, 35, 22)
        close.setGeometry(710, 0, 35, 22)
        YDldr.setGeometry(10, 70, 100, 90)
        ODldr.setGeometry(10, 160, 100, 90)
        Grbr.setGeometry(10, 250, 100, 90)
        credit.setGeometry(10, 360, 100, 30)

        self.tabWidget.setGeometry(120, 40, 620, 350)

        self.resize(760, 400)
        self.trayIcon.show()

        self.connect(cBox, QtCore.SIGNAL('activated(int)'), self.sayIndex)
        self.connect(close, QtCore.SIGNAL('clicked()'), self.goToTray)
        self.connect(credit, QtCore.SIGNAL('clicked()'), self.creditMsg)
        self.connect(minimize, QtCore.SIGNAL('clicked()'), self.showMinimized)
        self.connect(Grbr, QtCore.SIGNAL('clicked()'), self.runSiteGrabber)
        self.connect(YDldr, QtCore.SIGNAL('clicked()'),
                     self.YoutubeLinkDownload)
        self.connect(ODldr, QtCore.SIGNAL('clicked()'), self.fetchAndSaveUrl)
        self.connect(self.timer, QtCore.SIGNAL('timeout()'),
                     self.regulateDownload)
        self.timer.start(2000)

    def sayIndex(self, index):
        if index == 1:
            self.PARTS = 1
        elif not (index == 0):
            self.PARTS = 5 * (index - 1)

    def runingWin(self, index):
        if not (self.dLoads[index] == None):
            self.dLoads[index].flag = self.dLoads[index].flag | 0x0010

    def regulateDownload(self):
        for key in self.dLoads:
            flag = self.dLoads[key].flag
            if not (self.dLoads[key].free):
                self.tabWidget.updateEntry(self.dLoads[key].getInfo(),
                                           self.dLoads[key].downloaded,
                                           self.dLoads[key].timeLeft)
            if flag & 0x0002:
                self.dLoads[key].free = 0
                self.dLoads[key].flag = flag & 0xfffd
                self.dLoads[key].free = 1
                self.dLoads[key].obj.hide()
                self.downloads.delAction(key)
                self.tabWidget.updateEntry(self.dLoads[key].getInfo(),
                                           self.dLoads[key].downloaded, '0', 1)
            if flag & 0x0008:
                self.dLoads[key].obj.show()
                self.downloads.pushAction(key, self.dLoads[key].fileName, self)
                self.dLoads[key].flag = flag & 0xfff7
                self.tabWidget.makeEntry(self.dLoads[key].getInfo())
            if flag & 0x0100:
                self.downloads.pushAction(key, self.dLoads[key].fileName, self)
                self.dLoads[key].obj.show()
                self.dLoads[key].flag = flag & 0xfeff

            if flag & 0x0004:
                self.dLoads[key].free = 0
                self.dLoads[key].obj.hide()
                self.dLoads[key].flags = flag & 0xfffb
                self.dLoads[key].free = 1
                self.downloads.delAction(key)
                self.tabWidget.updateEntry(self.dLoads[key].getInfo(),
                                           int(self.dLoads[key].length), '0',
                                           1)
                self.dLoads[key].flag = flag & 0xfffb

            if flag & 0x0040:
                self.dLoads[key].free = 1
                self.dLoads[key].clear()
                self.downloads.delAction(key)
                ok = QtGui.QMessageBox(QtGui.QMessageBox.Information, 'Oops',
                                       "Fatal Error In Download",
                                       QtGui.QMessageBox.Ok, self,
                                       QtCore.Qt.FramelessWindowHint)
                ok.exec_()
                self.dLoads[key].flag = flag & 0xffbf

        if self.goTerminate == 1:
            if self.freeKey() == -1:
                sys.exit(0)
        self.timer.start(2000)

    def runSiteGrabber(self):
        ok = QtGui.QMessageBox(
            QtGui.QMessageBox.Information, 'Site Grabber',
            "Sorry This facility is currently unavilable .  You may contribute for it.",
            QtGui.QMessageBox.Ok, self, QtCore.Qt.FramelessWindowHint)
        ok.show()

    def freeKey(self):
        for key in self.dLoads:
            if self.dLoads[key].free == 1:
                return key
        return -1

    def loadPartition(self, url):
        pass

    def YoutubeLinkDownload(self):
        txt, ok = QtGui.QInputDialog.getText(self, 'YouTube Link',
                                             'YTube Link:',
                                             QtGui.QLineEdit.Normal, '',
                                             QtCore.Qt.FramelessWindowHint)
        if ok == True:
            if txt.startsWith('https://www.youtube.com'):
                key = self.freeKey()
                if key == -1:
                    obj = Interface(self.PARTS)
                else:
                    obj = self.dLoads[key]
                    obj.PARTS = self.PARTS
                    obj.clear()
                    del self.dLoads[key]

                thread.start_new_thread(obj.start_Download, (txt, self.wMutex))
                self.dLoads[self.links] = obj
                self.links = self.links + 1
            else:
                msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Oops.',
                                        "Not a valid YTube Url ",
                                        QtGui.QMessageBox.Ok, self,
                                        QtCore.Qt.FramelessWindowHint)
                msg.show()

    def downloadPartition(self, url, fileName, dt, tm, length):
        key = self.freeKey()
        if key == -1:
            obj = Interface(self.PARTS)
            key = self.links
            self.links = self.links + 1
        else:
            obj = self.dLoads[key]
            obj.PARTS = self.PARTS
            obj.clear()
            del self.dLoads[key]
        obj.url = url
        obj.fileName = fileName
        obj.dt = dt
        obj.tm = tm
        obj.length = length
        bit = 0
        if url.startswith('http://www.youtube.com'):
            bit = 1
        thread.start_new_thread(obj.start_from_Part, (self.wMutex, bit))
        self.dLoads[key] = obj

    def fetchAndSaveUrl(self, url='', bit=1):
        ok = True
        if len(url) == 0:
            url, ok = QtGui.QInputDialog.getText(self, 'Link',
                                                 'Download Link:',
                                                 QtGui.QLineEdit.Normal, '',
                                                 QtCore.Qt.FramelessWindowHint)
        if ok == True:
            key = self.freeKey()
            if key == -1:
                obj = Interface(self.PARTS)
                key = self.links
                self.links = self.links + 1
            else:
                obj = self.dLoads[key]
                obj.PARTS = self.PARTS
                obj.clear()
                del self.dLoads[key]

            thread.start_new_thread(obj.start_Download,
                                    (url, self.wMutex, bit))
            self.dLoads[key] = obj
        else:
            msg = QtGui.QMessageBox(QtGui.QMessageBox.Warning, 'Oops.',
                                    "Not a valid Url ", QtGui.QMessageBox.Ok,
                                    self, QtCore.Qt.FramelessWindowHint)
            msg.show()

    def createMenu(self):
        menu = QtGui.QMenu(self)

        self.downloads = Menu("Downloads", self)
        miniToTray = QtGui.QAction("Minimize To Tray", self)
        setting = QtGui.QAction("Preference", self)
        cLoc = QtGui.QAction("Change Downloads Destination", self)
        quit = QtGui.QAction("Quit", self)

        miniToTray.setShortcut('Ctrl+M')
        menu.addMenu(self.downloads)
        menu.addSeparator()
        menu.addAction(miniToTray)
        menu.addAction(setting)
        menu.addSeparator()
        menu.addAction(cLoc)
        menu.addSeparator()
        menu.addAction(quit)

        self.menuBtn.setMenu(menu)
        self.connect(miniToTray, QtCore.SIGNAL('triggered()'), self.goToTray)
        self.connect(setting, QtCore.SIGNAL('triggered()'), self.getSetting)
        self.connect(cLoc, QtCore.SIGNAL('triggered()'), self.changeLoc)
        self.connect(quit, QtCore.SIGNAL('triggered()'), self.safeExit)

    def changeLoc(self):
        data = self.dLocation
        if not (os.path.exists(data)):
            data = '/home'
        fD = QtGui.QFileDialog(self, 'Get Download Destination', data, '')
        fD.setOption(QtGui.QFileDialog.ShowDirsOnly, True)
        fD.setFileMode(2)
        fD.resize(500, 300)
        fLoc = ''
        if fD.exec_():
            if len(fD.selectedFiles()) > 0:
                fLoc = fD.selectedFiles()[0]
        fLoc = str(fLoc)
        if len(fLoc) > 0:
            if os.path.exists(fLoc):
                self.dLocation = fLoc
                f = open(os.getcwd() + '/Locale/desF', 'w')
                f.write(fLoc)
                f.close()
                for key in self.dLoads:
                    if not (self.dLoads[key] == None):
                        self.dLoads[key].dLocation = fLoc

    def getSetting(self):
        self.pref.show()

    def addTrayIcon(self):
        self.trayIcon.setIcon(QtGui.QIcon('image/tray.png'))

        menu = QtGui.QMenu(self)
        showWin = QtGui.QAction("Show Window", self)
        quit = QtGui.QAction("Quit", self)

        menu.addAction(showWin)
        menu.addMenu(self.downloads)
        menu.addAction(quit)

        self.trayIcon.setContextMenu(menu)
        self.connect(showWin, QtCore.SIGNAL('triggered()'), self.getOutOfTray)
        self.connect(quit, QtCore.SIGNAL('triggered()'), self.safeExit)

    def mousePressEvent(self, event):
        self.posMove = event.pos()

    def mouseMoveEvent(self, event):
        if self.posMove:
            self.move(self.pos().x() + event.pos().x() - self.posMove.x(),
                      self.pos().y() + event.pos().y() - self.posMove.y())

    def mouseReleaseEvent(self, event):
        self.posMove = None

    def creditMsg(self):
        ok = QtGui.QMessageBox(
            QtGui.QMessageBox.Information, 'LDM Community',
            "By using this application you are contributing to this development.Thanks a lot for it.\nHope you'll enjoy & share your experience\n-Anand Kumar\nEfficience\nSubscribe to  (linkinAnand.blogspot.com) to get all the latest information.\nDeveloper (twitter.com/EfficienceAnand)\ncurrently at IIITA",
            QtGui.QMessageBox.Ok, self, QtCore.Qt.FramelessWindowHint)
        ok.show()

    def goToTray(self):
        if self.isVisible():
            self.hide()

    def getOutOfTray(self):
        if not (self.isVisible()):
            self.show()

    def safeExit(self):
        gT = True
        for key in self.dLoads:
            if self.dLoads[key].free == 0:
                gT = False
                break
        if gT == True:
            sys.exit(0)
        else:
            msg = QtGui.QMessageBox(
                QtGui.QMessageBox.Question, '!!',
                "Some Download process are still running\nWould you still like to quit the application ?",
                QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, self,
                QtCore.Qt.FramelessWindowHint)
            ok = msg.exec_()
            if ok == QtGui.QMessageBox.Yes:
                self.goTerminate = True
                for key in self.dLoads:
                    self.dLoads[key].flag | 0x0080
class Crawler(QtGui.QWidget):
	signalClickedToLoadUrl = QtCore.Signal(QtCore.QUrl)
	
	def __init__(self, width = 800, height = 600):
		super(Crawler, self).__init__()
		self.setGeometry(10, 10, width, height)
		self.setupUI()
		
	def setupUI(self) :
		self.mainHBoxLayout = QtGui.QHBoxLayout()
		self.mainRVBoxLayout = QtGui.QVBoxLayout()
		self.mainLVBoxLayout = QtGui.QVBoxLayout()
		self.executeCrawler = QtGui.QPushButton("Get Content!!!")
		self.urlBarLineEdit = QtGui.QLineEdit("http://www2.tpa.edu.tw/tpaedu/Home/login.asp")
		self.myWebView = WebView()
		self.myTabWidget = TabWidget()
		
		#self.myWebView.settings().setDefaultTextEncoding("big5")
		self.myWebView.show()
		self.myTabWidget.addTab(self.myWebView, "my Web View")
		
		self.mainLVBoxLayout.addWidget(self.urlBarLineEdit)
		self.mainLVBoxLayout.addWidget(self.myTabWidget)
		self.mainRVBoxLayout.addWidget(self.executeCrawler)
		
		self.mainHBoxLayout.addLayout(self.mainLVBoxLayout)
		self.mainHBoxLayout.addLayout(self.mainRVBoxLayout)
		self.setLayout(self.mainHBoxLayout)
		
		self.executeCrawler.clicked.connect(self.slotClickedToLoadUrl)
		self.signalClickedToLoadUrl.connect(self.slotLoadUrl)
		self.myWebView.loadFinished.connect(self.slotWebViewLoadFinished)
		
		self.show()
	
	@QtCore.Slot()
	def slotClickedToLoadUrl(self) :
		print(self.urlBarLineEdit.text())
		self.signalClickedToLoadUrl.emit(QtCore.QUrl(self.urlBarLineEdit.text()))
	
	@QtCore.Slot(QtCore.QUrl)
	def slotLoadUrl(self, qUrl) :
		self.myWebView.load(qUrl)
	
	@QtCore.Slot(bool)
	def slotWebViewLoadFinished(self, isFinished) :
		if isFinished :
			self.urlBarLineEdit.setText(self.myWebView.url().toString())
			pageFrames = self.myWebView.page().mainFrame().childFrames()
			print("base Url := " + self.myWebView.page().mainFrame().baseUrl().toString())
			
			if self.myWebView.page().mainFrame().baseUrl().toString() == "http://www2.tpa.edu.tw/tpaedu/default.asp" :
				print("it is tpa local net")
				for frame in pageFrames :
					print(frame.frameName())
					#print(frame.toHtml())
					elements = frame.findAllElements("td")
					print(elements.count())
					for index in range(elements.count()) :
						"""print("elements" + str(index))
						print(elements.at(index + 1).tagName())
						print(elements.at(index + 1).firstChild().tagName())
						print(elements.at(index + 1).firstChild().nextSibling().tagName())
						print(elements.at(index + 1).firstChild().nextSibling().nextSibling().tagName())
						print(elements.at(index + 1).firstChild().nextSibling().nextSibling().nextSibling().tagName())
						print(str(type(elements.at(index + 1).firstChild().nextSibling().nextSibling().nextSibling().nextSibling())))"""
						findAllElementsChild(elements.at(index + 1).firstChild())
						
					if frame.frameName() == "logo" :
						pass
					elif frame.frameName() == "menu" :
						# get menu for javascript robot action
						pass
					elif frame.frameName() == "main" :
						# get main content to crawler data
						pass
					elif self.myWebView.page().mainFrame().baseUrl().toString() == "http://www2.tpa.edu.tw/tpaedu/Home/login.asp" :
						pass
				pass
class Server(QtNetwork.QTcpServer):
    addNewThread = QtCore.Signal(MoniterObject)

    # basic initial
    # private object :
    # 	widget : TabWidget for WebView
    #	monitor : A thread object for monite all connection and release finished connection
    # connections :
    #	when main widget close, it will shutdown server instantly
    #	a new connection handler
    #	monitor add new object event
    def __init__(self):
        super(Server, self).__init__()
        self.widget = TabWidget()
        self.monitor = MoniterThread()
        self.widget.closeSignal.connect(self.stopServer)
        self.newConnection.connect(self.newConnectionHandler)
        self.addNewThread.connect(self.monitor.addNewThread)
        pass

    # start monitor, show widget, start service
    def run(self):
        self.monitor.start()
        self.widget.show()
        self.listen(QtNetwork.QHostAddress("127.0.0.1"), 5000)

    @QtCore.Slot()
    def newConnectionHandler(self):
        newTcpSocket = self.nextPendingConnection(
        )  # get new connection socket
        connection = Connection(
            newTcpSocket)  # create a new connection delegate object
        crossThread = CrossThread()  # create connection thread
        self.widget.addTab(str(
            crossThread.currentThreadId()), connection.widget(
            ))  # insert connection attach widget to server main widget
        connection.closeConnection.connect(
            self.widget.deleteTab
        )  # connect connection close to remove widget of server main widget
        crossThread.finishedSignal.connect(
            self.monitor.deleteThread
        )  # when a thread dead or finish its job, it will tell monitor to delete it.
        crossThread.startedSignal.connect(
            connection.service)  # inform new connection thread start service.
        connection.moveToThread(
            crossThread)  # let connection run in new thread
        moniterObject = MoniterObject(
            crossThread,
            connection)  # create a monitor object for monitor thread
        self.addNewThread.emit(
            moniterObject)  # make monitor thread registe a new monitor object
        crossThread.start()  # new connection thread start running

    # don't stop directly, it will wait all thread finished and stop safely
    @QtCore.Slot()
    def stopServer(self):
        self.monitor.deleteAll()

        while not self.monitor.isFinished():
            pass

        print("Is monitor thread is end ? : " + str(self.monitor.isFinished()))

        self.close()
        self.widget.deleteLater()
        self.deleteLater()
class Crawler(QtGui.QWidget):
    signalClickedToLoadUrl = QtCore.Signal(QtCore.QUrl)

    def __init__(self, width=800, height=600):
        super(Crawler, self).__init__()
        self.setGeometry(10, 10, width, height)
        self.setupUI()

    def setupUI(self):
        self.mainHBoxLayout = QtGui.QHBoxLayout()
        self.mainRVBoxLayout = QtGui.QVBoxLayout()
        self.mainLVBoxLayout = QtGui.QVBoxLayout()
        self.executeCrawler = QtGui.QPushButton("Get Content!!!")
        self.urlBarLineEdit = QtGui.QLineEdit(
            "http://www2.tpa.edu.tw/tpaedu/Home/login.asp")
        self.myWebView = WebView()
        self.myTabWidget = TabWidget()

        #self.myWebView.settings().setDefaultTextEncoding("big5")
        self.myWebView.show()
        self.myTabWidget.addTab(self.myWebView, "my Web View")

        self.mainLVBoxLayout.addWidget(self.urlBarLineEdit)
        self.mainLVBoxLayout.addWidget(self.myTabWidget)
        self.mainRVBoxLayout.addWidget(self.executeCrawler)

        self.mainHBoxLayout.addLayout(self.mainLVBoxLayout)
        self.mainHBoxLayout.addLayout(self.mainRVBoxLayout)
        self.setLayout(self.mainHBoxLayout)

        self.executeCrawler.clicked.connect(self.slotClickedToLoadUrl)
        self.signalClickedToLoadUrl.connect(self.slotLoadUrl)
        self.myWebView.loadFinished.connect(self.slotWebViewLoadFinished)

        self.show()

    @QtCore.Slot()
    def slotClickedToLoadUrl(self):
        print(self.urlBarLineEdit.text())
        self.signalClickedToLoadUrl.emit(
            QtCore.QUrl(self.urlBarLineEdit.text()))

    @QtCore.Slot(QtCore.QUrl)
    def slotLoadUrl(self, qUrl):
        self.myWebView.load(qUrl)

    @QtCore.Slot(bool)
    def slotWebViewLoadFinished(self, isFinished):
        if isFinished:
            self.urlBarLineEdit.setText(self.myWebView.url().toString())
            pageFrames = self.myWebView.page().mainFrame().childFrames()
            print("base Url := " +
                  self.myWebView.page().mainFrame().baseUrl().toString())

            if self.myWebView.page().mainFrame().baseUrl().toString(
            ) == "http://www2.tpa.edu.tw/tpaedu/default.asp":
                print("it is tpa local net")
                for frame in pageFrames:
                    print(frame.frameName())
                    #print(frame.toHtml())
                    elements = frame.findAllElements("td")
                    print(elements.count())
                    for index in range(elements.count()):
                        """print("elements" + str(index))
						print(elements.at(index + 1).tagName())
						print(elements.at(index + 1).firstChild().tagName())
						print(elements.at(index + 1).firstChild().nextSibling().tagName())
						print(elements.at(index + 1).firstChild().nextSibling().nextSibling().tagName())
						print(elements.at(index + 1).firstChild().nextSibling().nextSibling().nextSibling().tagName())
						print(str(type(elements.at(index + 1).firstChild().nextSibling().nextSibling().nextSibling().nextSibling())))"""
                        findAllElementsChild(
                            elements.at(index + 1).firstChild())

                    if frame.frameName() == "logo":
                        pass
                    elif frame.frameName() == "menu":
                        # get menu for javascript robot action
                        pass
                    elif frame.frameName() == "main":
                        # get main content to crawler data
                        pass
                    elif self.myWebView.page().mainFrame().baseUrl().toString(
                    ) == "http://www2.tpa.edu.tw/tpaedu/Home/login.asp":
                        pass
                pass
Beispiel #14
0
class MainForm(QDialog):
   mythControl = None
   def __init__(self, parent = None):
      QDialog.__init__(self, parent)
      self.previousChannel = None
      
      self.setupUI()
      
      if settings['firstRun']:
         self.initialSetup()
      
      self.mythDB = MythDB(settings['dbHost'], settings['dbUser'], settings['dbPassword'])
      self.mythControl = MythControl(self.mythDB)
      self.refreshShowList()
      
      self.setWindowTitle('Mythnimal')
      self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowMinMaxButtonsHint)
      self.resize(1024, 600)
      self.mainMenu.focus()
      self.show()
      
      
   def setupUI(self):
      self.tabLayout = QVBoxLayout(self)
      self.tabs = TabWidget()
      self.tabLayout.addWidget(self.tabs)
      self.mainMenuTab = self.tabs.createTab('Main Menu')
      self.mainMenuLayout = QVBoxLayout(self.mainMenuTab)
      
      self.mainMenu = MenuWidget()
      self.mainMenu.selected.connect(self.mainMenuSelected)
      self.mainMenu.exit.connect(self.close)
      self.mainMenu.add(SimpleMenuItem('Live TV'))
      self.mainMenu.add(SimpleMenuItem('Watch Recordings'))
      self.mainMenu.add(SimpleMenuItem('Settings'))
      self.mainMenuLayout.addWidget(self.mainMenu)
      
      self.createRecordingsTab()
      self.createSettingsTab()
      
      self.messageDialog = MessageDialog(self)

      
   def createRecordingsTab(self):
      self.recordingsTab = self.tabs.createTab('Recordings')
      self.columnLayout = QHBoxLayout(self.recordingsTab)
      
      self.showMenu = MenuWidget()
      self.showMenu.selected.connect(self.showSelected)
      self.showMenu.exit.connect(self.exitShowMenu)
      self.showMenu.selectionChanged.connect(self.filterByShow)
      self.columnLayout.addWidget(self.showMenu, 1)
      
      self.programMenu = MenuWidget()
      self.programMenu.selected.connect(self.programSelected)
      self.programMenu.exit.connect(self.exitProgramMenu)
      self.programMenu.selectionChanged.connect(self.displayProgramDetails)
      self.columnLayout.addWidget(self.programMenu, 1)
      
      self.programInfoLayout = QVBoxLayout()
      self.programThumbnail = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programThumbnail)
      
      self.programChannel = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programChannel)
      self.programTitle = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programTitle)
      self.programSubtitle = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programSubtitle)
      self.programStartTime = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programStartTime)
      self.programTime = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programTime)
      self.programDescription = self.wrappedLabel()
      self.programInfoLayout.addWidget(self.programDescription, 1)
      
      self.columnLayout.addLayout(self.programInfoLayout, 1)
      
      
   def createSettingsTab(self):
      self.settingsTab = self.tabs.createTab('Settings')
      
      self.settingsLayout = QVBoxLayout(self.settingsTab)
      
      self.settingsInputLayout = QHBoxLayout()
      self.settingsLayout.addLayout(self.settingsInputLayout)
      
      self.dbGroup = QGroupBox('DB/Filesystem')
      self.dbGroupLayout = QVBoxLayout()
      self.dbGroup.setLayout(self.dbGroupLayout)
      self.settingsInputLayout.addWidget(self.dbGroup)
      
      self.dbHostInput = QLineEdit()
      self.dbGroupLayout.addWidget(PairWidget('DB Hostname', self.dbHostInput))
      self.dbUserInput = QLineEdit()
      self.dbGroupLayout.addWidget(PairWidget('DB Username', self.dbUserInput))
      self.dbPasswordInput = QLineEdit()
      self.dbGroupLayout.addWidget(PairWidget('DB Password', self.dbPasswordInput))
      self.fileDirInput = QLineEdit()
      self.dbGroupLayout.addWidget(PairWidget('Local Myth File Directory', self.fileDirInput))
      
      self.miscGroup = QGroupBox('Miscellaneous')
      self.miscGroupLayout = QVBoxLayout()
      self.miscGroup.setLayout(self.miscGroupLayout)
      self.settingsInputLayout.addWidget(self.miscGroup)
      
      self.mpvInput = QLineEdit()
      self.miscGroupLayout.addWidget(PairWidget('MPV Command', self.mpvInput))
      
      self.bufferTimeInput = QSpinBox()
      self.miscGroupLayout.addWidget(PairWidget('Buffer Time', self.bufferTimeInput))
      
      self.settingsButtonLayout = QHBoxLayout()
      self.settingsLayout.addLayout(self.settingsButtonLayout)
      
      self.saveSettingsButton = QPushButton('Save')
      self.saveSettingsButton.clicked.connect(self.saveSettings)
      self.settingsButtonLayout.addWidget(self.saveSettingsButton)
      
      self.discardSettingsButton = QPushButton('Discard')
      self.discardSettingsButton.clicked.connect(self.discardSettings)
      self.settingsButtonLayout.addWidget(self.discardSettingsButton)
      
      
   def wrappedLabel(self):
      label = ScaledLabel()
      label.setWordWrap(True)
      return label
      
      
   def refreshShowList(self):
      self.showMenu.reset()
      newItem = SimpleMenuItem('[All]')
      newItem.id = '%'
      self.showMenu.add(newItem)
      self.showFilter = '%'
      shows = self.mythDB.showList()
      for i in shows:
         self.showMenu.add(SimpleMenuItem(i.title))
         
      self.refreshProgramList()
         
   def refreshProgramList(self):
      self.programMenu.reset()
      programs = self.mythDB.programList(self.showFilter)
      for i in programs:
         self.programMenu.add(ProgramMenuItem(i))
         
         
   def filterByShow(self, index):
      item = self.showMenu.selectedItem()
      self.showFilter = item.id
      self.refreshProgramList()
         
         
   def showSelected(self):
      self.programMenu.focus()
      self.displayProgramDetails()
      
   def exitProgramMenu(self):
      self.showMenu.focus()
      
      
   def exitShowMenu(self):
      self.tabs.setCurrentWidget(self.mainMenuTab)
      
      
   def displayProgramDetails(self):
      selected = self.programMenu.selectedItem()
      if selected is None:
         return
      details = self.mythDB.getProgram(selected.id)
      if details is None:
         self.refreshProgramList()
         return
      channel = self.mythDB.getChannel(details.chanid)
      filename = self.getFullPath(details.basename)
      filename += '.png'
      self.programThumbnail.setPixmap(QPixmap(filename).scaledToWidth(self.width() / 3))
      if channel is not None:
         self.programChannel.setText(channel.channum + ' ' + channel.name)
      else:
         self.programChannel.setText('NA')
      self.programTitle.setText(details.title)
      self.programSubtitle.setText(details.subtitle)
      startTime = self.mythDB.fromUTC(details.starttime).strftime('%Y-%m-%d %I:%M %p')
      self.programStartTime.setText(startTime)
      self.programTime.setText(str(int((details.endtime - details.starttime).total_seconds() / 60)) + ' minutes')
      self.programDescription.setText(details.description)
      
      
   # Index is ignored
   def programSelected(self, index):
      self.startPlayer(self.programMenu.selectedItem().id, live = False)
      
      
   # TODO Needs to be reimplemented using MenuItem signals
   def mainMenuSelected(self, index):
      if index == 0:
         self.startLiveTV()
      elif index == 1:
         self.refreshShowList()
         self.tabs.setCurrentWidget(self.recordingsTab)
      elif index == 2:
         self.showSettingsTab()
      else:
         print 'Unimplemented main menu item selected'
         
         
   def populateSettings(self):
      self.dbHostInput.setText(settings['dbHost'])
      self.dbUserInput.setText(settings['dbUser'])
      self.dbPasswordInput.setText(settings['dbPassword'])
      self.fileDirInput.setText(settings['mythFileDir'])
      self.mpvInput.setText(settings['mpv'])
      self.bufferTimeInput.setValue(settings['bufferTime'])
      
   def showSettingsTab(self):
      self.populateSettings()
      self.tabs.setCurrentWidget(self.settingsTab)
   
   
   def saveSettings(self):
      settings['dbHost'] = str(self.dbHostInput.text())
      settings['dbUser'] = str(self.dbUserInput.text())
      settings['dbPassword'] = str(self.dbPasswordInput.text())
      settings['mythFileDir'] = str(self.fileDirInput.text())
      settings['mpv'] = str(self.mpvInput.text())
      settings['bufferTime'] = self.bufferTimeInput.value()
      settings.save()
      if settings['firstRun']:
         self.initConfig.hide()
      self.tabs.setCurrentWidget(self.mainMenuTab)
   
   def discardSettings(self):
      self.tabs.setCurrentWidget(self.mainMenuTab)
      
      
   def closeEvent(self, event):
      settings.save()
      
      
   def resizeEvent(self, event):
      ScaledLabel.formHeight = event.size().height()
      
      
   def initialSetup(self):
      self.initConfig = QDialog()
      self.initConfig.setLayout(self.settingsLayout)
      self.populateSettings()
      self.initConfig.exec_()
      self.settingsTab.setLayout(self.settingsLayout)
      settings['firstRun'] = False
      
      
   def startLiveTV(self):
      self.messageDialog.showMessage('Buffering...')
      filename = self.mythControl.startLiveTV(qApp.processEvents)
      self.messageDialog.hide()
      self.startPlayer(filename, live = True)
      
         
   def changeChannel(self, channel):
      self.messageDialog.showMessage('Buffering...')
      self.previousChannel = self.mythControl.currentChannel
      filename = self.mythControl.changeChannel(channel, qApp.processEvents)
      # This is highly unlikely, but possible
      if filename is None:
         self.messageDialog.showMessageTimed('Channel change failed')
      self.messageDialog.hide()
      self.startPlayer(filename, live = True)
      
      
   def startPlayer(self, filename, live = False, startAtEnd = False):
      if filename is not None:
         playerX = self.x() + self.width() / 2
         playerY = self.y() + self.height() / 2
         self.player = Player(playerX, playerY, filename, self.mythDB, startAtEnd)
         self.player.finished.connect(self.activateWindow)
         if live:
            if self.previousChannel is None:
               self.previousChannel = self.mythControl.currentChannel
            self.player.previousChannel = self.previousChannel
            self.player.finished.connect(self.playerStopped)
            self.player.channelChange.connect(self.changeChannel)
            self.player.seekedPastStart.connect(self.playPreviousInChain)
            self.player.toggleRecording.connect(self.toggleRecording)
            self.player.currentChannel = self.mythControl.currentChannel
            
            
   def playerStopped(self, eof):
      if not eof:
         self.mythControl.stopLiveTV()
         self.activateWindow()
      else: # Go to the next live TV recording
         nextChain = None
         while nextChain == None:
            i, chain, currentChain = self.getCurrentChain()
            if i + 1 < len(chain):
               nextChain = chain[i + 1]
            else:
               print 'Waiting for next program to start'
         nextProgram = self.mythDB.getProgramByChain(nextChain)
         self.player.emitFinished = False
         self.player.end(eof = False)
         self.startPlayer(nextProgram.basename, live = True)
         
         
   def playPreviousInChain(self):
      i, chain, currentChain = self.getCurrentChain()
      if i > 0:
         nextProgram = self.mythDB.getProgramByChain(chain[i - 1])
         self.player.emitFinished = False
         self.player.end(eof = False)
         self.startPlayer(nextProgram.basename, live = True, startAtEnd = True)
   
   
   def getCurrentChain(self):
      currentProgram = self.mythDB.getProgram(self.player.filename)
      chain = self.mythDB.getTVChain(self.mythControl.chain)
      for i, entry in enumerate(chain):
         if entry.chanid == currentProgram.chanid and entry.starttime == currentProgram.starttime:
            return i, chain, entry
            
            
   def toggleRecording(self):
      program = self.mythDB.getProgram(self.player.filename)
      self.mythControl.toggleRecording(program)
      if self.mythControl.recordCurrent:
         self.player.showMessage('Recording current program')
      else:
         self.player.showMessage('Not recording current program')
      
            
   def keyPressEvent(self, event):
      key = event.key()
      if self.programMenu.hasFocus():
         if key == Qt.Key_M:
            self.showProgramMenu()
         
         
   def showProgramMenu(self):
      self.menuDialog = QDialog(self)
      menuLayout = QVBoxLayout(self.menuDialog)
      
      selected = self.mythDB.getProgram(self.programMenu.selectedItem().id)
      title = ScaledLabel(selected.title)
      menuLayout.addWidget(title)
      subtitle = ScaledLabel(selected.subtitle)
      menuLayout.addWidget(subtitle)
      
      programOptions = MenuWidget(self)
      programOptions.exit.connect(self.menuDialog.close)
      menuLayout.addWidget(programOptions)
      
      item = SimpleMenuItem('Delete')
      item.selected.connect(self.deleteSelected)
      programOptions.add(item)
      item = SimpleMenuItem('Delete and re-record')
      item.selected.connect(self.deleteAndRerecord)
      programOptions.add(item)
      
      self.menuDialog.exec_()
      self.menuDialog = None # For some reason not doing this results in segfaults
      
   def deleteSelected(self):
      self.deleteSelectedProgram(False)
      self.menuDialog.close()
   
   def deleteAndRerecord(self):
      self.deleteSelectedProgram(True)
      self.menuDialog.close()
      
      
   def deleteSelectedProgram(self, rerecord):
      selected = self.programMenu.selectedItem()
      selectedProgram = self.mythDB.getProgram(selected.id)
      self.mythControl.deleteProgram(selectedProgram, rerecord)
      self.programMenu.remove(selected)
      
      
   def getFullPath(self, basename):
      return os.path.join(settings['mythFileDir'], basename)