#!/usr/bin/env python
# -*- coding: utf-8 -*-
import gi

gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, Notify, Gdk
import tushare as ts
import time
import gp_xml
import sound
import op_window
import fenxi_xml
import os


# global names

class GP:
    def __init__(self, builder):
        self.must_save = False  # 是否需要保存数据,'0'不需要,'1'需要
        self.timer = None  # 监控时钟
        self.show_timer = None  # 显示name列时钟
        self.monitor_time = 20000
        self.edit_save = False  # 编辑按钮状态
        self.monitor_button_onoff = 0  # 监控按钮状态
        self.ori_visible = False  # 记录第一列显示/隐藏状态
        self.nt = None
        self.ori_text = ''
        self.alert_list = []
        self.monitor_menu_label = "未监控"
        self.current_gp_code = ""   #当前选中的股票代码
        self.data_file_path = "data_file/example"

        handlers = {
            "onDeleteEvent": self.hind_window,
            "on_monitor_button_clicked": self.monitor_button_clicked,
            "on_edit_button_clicked": self.edit_button_clicked,
            "on_button2_clicked": self.clearall_button_clicked,
            "on_menuitem3_activate": self.windowmenu_fenxi_activated,
            "on_imagemenuitem5_activate": Gtk.main_quit,
            "on_imagemenuitem8_activate": self.editmenu_append_activated,
            "on_imagemenuitem9_activate": self.editmenu_delete_activated,
            "on_menuitem8_activate": self.editmenu_cancel_activated,
            "on_imagemenuitem10_activate": self.viewmenu_log_activated,
            "on_statusicon1_button_press_event": self.statusicon_button_pressed,
            "on_statusicon1_popup_menu": self.statusicon_popup_menu,
            "on_treeview2_key_press_event": self.treeview2_key_pressed,
            "on_treeview2_button_press_event": self.treeview2_button_preesed,
            "on_applicationwindow1_delete_event": self.applicationwindow1_delete,
            "on_menuitem9_toggled": self.viewmenu_first_column_toggled,
            "on_menuitem7_activate": self.treeview_popmenu_hy_activated,
            "on_menuitem5_activate": self.treeview_popmenu_buy_activated,
            "on_menuitem6_activate": self.treeview_popmenu_sell_activated,
            "on_applicationwindow2_delete_event": self.applicationwindow2_detete_event,
            "on_button4_clicked": self.applicationwindow2_edit_button_clicked,
            "on_button6_clicked": self.button_d_clicked,
            "on_button7_clicked": self.button_30f_clicked,
            "on_button8_clicked": self.button_5f_clicked,

        }
        builder.connect_signals(handlers)

        # get object from builder
        self.window = builder.get_object("window1")
        self.window.show_all()

        self.treeview = builder.get_object("treeview2")
        self.textview = builder.get_object("textview1")
        self.noteview = builder.get_object("textview2")
        self.monitor_button = builder.get_object('button1')
        self.edit_button = builder.get_object('button3')
        self.app_window = builder.get_object("applicationwindow1")
        self.dw = builder.get_object("dialog1")
        self.hy_window = builder.get_object("applicationwindow2")

        self.noteview_buffer = self.noteview.get_buffer()
        self.noteview_buffer.connect("changed", self.noteview_changed)

        # enable drag and drop
        self.TARGETS = [("int", 0, 0)]
        self.treeview.connect("drag_data_get", self.drag_data_get_data)
        self.treeview.connect("drag_data_received", self.drag_data_received_data)

        # treeview selection
        self.treeselection = self.treeview.get_selection()
        self.treeselection.connect("changed", self.treeselection_changed)

        self.statusicon = builder.get_object('statusicon1')
        self.statusicon.set_from_stock(Gtk.STOCK_HOME)
        self.statusicon.set_visible(True)
        self.statusicon.set_tooltip_markup('markup')
        self.statusicon.set_tooltip_text('text')

        self.liststore = Gtk.ListStore(str, str, str, str, str, str, str, str, str)
        self.treeview.set_model(self.liststore)
        self.gp_data = gp_xml.read_xml(self.data_file_path + "/gp_data.xml")
        for data in self.gp_data:
            self.liststore.append([data[0], data[1], "", data[2], data[3], data[4], 'black', 'black', data[5]])

        self.col1 = Gtk.TreeViewColumn('name')
        col2 = Gtk.TreeViewColumn('code')
        col3 = Gtk.TreeViewColumn('current')
        col4 = Gtk.TreeViewColumn('upto')
        col5 = Gtk.TreeViewColumn('downto')

        self.treeview.append_column(self.col1)
        self.treeview.append_column(col2)
        self.treeview.append_column(col3)
        self.treeview.append_column(col4)
        self.treeview.append_column(col5)

        self.cell1 = Gtk.CellRendererText()
        self.cell2 = Gtk.CellRendererText()
        self.cell2.connect('edited', self.cell_edited, 1)
        self.cell2.connect('editing_started', self.cell_editing_started)
        cell3 = Gtk.CellRendererText()
        self.cell4 = Gtk.CellRendererText()
        self.cell4.set_property('editable', True)
        self.cell4.connect('edited', self.cell_edited, 3)
        self.cell4.connect('editing_started', self.cell_editing_started)
        self.cell5 = Gtk.CellRendererText()
        self.cell5.set_property('editable', True)
        self.cell5.connect('edited', self.cell_edited, 4)
        self.cell5.connect('editing_started', self.cell_editing_started)

        self.col1.pack_start(self.cell1, True)
        col2.pack_start(self.cell2, True)
        col3.pack_start(cell3, True)
        col4.pack_start(self.cell4, True)
        col5.pack_start(self.cell5, True)

        self.col1.add_attribute(self.cell1, 'text', 0)
        self.col1.set_visible(False)
        self.ori_visible = False
        col2.add_attribute(self.cell2, 'text', 1)
        col3.add_attribute(cell3, 'text', 2)
        col4.add_attribute(self.cell4, 'text', 3)
        col4.add_attribute(self.cell4, 'foreground', 6)
        col5.add_attribute(self.cell5, 'text', 4)
        col5.add_attribute(self.cell5, 'foreground', 7)

        return

    """--------------------------------------行业窗口start--------------------------------"""
    def applicationwindow2_detete_event(self, widget, event):
        button = builder.get_object("button4")
        button.set_label(Gtk.STOCK_EDIT)
        self.hy_window_code.set_text("")
        self.hy_window_name.set_text("")
        self.hy_window_date.set_text("")
        self.hy_window_info_buffer.set_text("")
        self.hy_window.set_visible(False)
        return True

    def applicationwindow2_edit_button_clicked(self, button):
        bl = button.get_label()
        if bl == "gtk-edit":
            self.hy_window_code.set_editable(True)
            self.hy_window_name.set_editable(True)
            self.hy_window_date.set_text(time.strftime("%Y-%m-%d", time.gmtime()))
            self.hy_window_info.set_editable(True)
            button.set_label(Gtk.STOCK_SAVE)
        else:
            self.hy_window_code.set_editable(False)
            self.hy_window_name.set_editable(False)
            self.hy_window_info.set_editable(False)
            button.set_label(Gtk.STOCK_EDIT)
            hy = ""
            #保存分析
            if self.ori_hy == "":   #当前股票没有行业代码
                hy = self.hy_window_code.get_text()
                self.zhishus[hy]=[self.hy_window_code.get_text(),self.hy_window_name.get_text(), self.hy_window_date.get_text(),\
                                  "hy", self.hy_window_info_buffer.get_text(self.hy_window_info_buffer.get_start_iter(),\
                                                                            self.hy_window_info_buffer.get_end_iter(), True)]
                self.ori_hy = hy
            else:   #当前股票已经含有行业代码
                hy = self.hy_window_code.get_text() #获取当前填入的行业代码
                self.zhishus[self.ori_hy]=[self.hy_window_code.get_text(),self.hy_window_name.get_text(), self.hy_window_date.get_text(), \
                                           "hy", self.hy_window_info_buffer.get_text(self.hy_window_info_buffer.get_start_iter(),\
                                                                                     self.hy_window_info_buffer.get_end_iter(), True)]

            self.liststore.set_value(self.current_iter,8, hy)
            fenxi_xml.write_xml(self.data_file_path + "/fenxi.xml", self.zhunze, self.zhishus)

            #根据liststore数据生成gp_data用于写入gp_data.xml
            """treeiter = self.liststore.get_iter_first()
            gp_data = []
            while treeiter != None:
                gp_data.append([self.liststore.get_value(treeiter, 0), self.liststore.get_value(treeiter, 1),
                                self.liststore.get_value(treeiter, 3), self.liststore.get_value(treeiter, 4),
                                self.liststore.get_value(treeiter, 5), self.liststore.get_value(treeiter, 8)])
                treeiter = self.liststore.iter_next(treeiter)
            gp_xml.write_xml("gp_data.xml", gp_data )"""
            self.save_xml("gp_data.xml")

        return True

    """--------------------------------------行业窗口end----------------------------------"""

    def progress_timeout(self):
        # get gp price
        treeiter = self.liststore.get_iter_first()
        self.gp_code = []
        while treeiter != None:
            self.gp_code.append([treeiter, self.liststore.get_value(treeiter, 1)])
            treeiter = self.liststore.iter_next(treeiter)

        # stock code list
        code_list = []
        for item in self.gp_code:
            code_list.append(item[1])

        # us tushare get price
        df = ts.get_realtime_quotes(code_list)

        # set liststore data
        i = 0
        for item in self.gp_code:
            self.liststore.set_value(item[0], 2, df['price'][i])
            i += 1

        # price monitor
        treeiter = self.liststore.get_iter_first()
        text = ''
        alert_onoff = 0  # 是否发出警告
        while treeiter != None:
            current = float(self.liststore.get_value(treeiter, 2))
            upto = self.liststore.get_value(treeiter, 3)
            downto = self.liststore.get_value(treeiter, 4)
            gp_code = self.liststore.get_value(treeiter, 1)
            if upto != "":
                upto = float(upto)
                if current >= upto and (gp_code in self.alert_list) == False:
                    text += gp_code + ' up to ' + str(current) + '   '
                    alert_onoff = 1
                    self.liststore.set_value(treeiter, 6, "red")

            if downto != "":
                downto = float(downto)
                if current <= downto and (gp_code in self.alert_list) == False:
                    text += gp_code + ' down to ' + str(current) + '   '
                    alert_onoff = 1
                    self.liststore.set_value(treeiter, 7, "green")

            if alert_onoff == 1:
                self.alert_list.append(gp_code)

            treeiter = self.liststore.iter_next(treeiter)

        if text != '' and alert_onoff == 1:
            textbuffer = self.textview.get_buffer()
            enditer = textbuffer.get_end_iter()
            logtext = time.strftime("%Y %m %d %H:%M:%S", time.localtime()) + "  " + text + '\n'
            textbuffer.insert(enditer, logtext, len(logtext))

            # 清除选中条目，便于查看预警
            selection = self.treeview.get_selection()
            selection.unselect_all()

            self.show_notify(text)
            self.statusicon.set_from_stock(Gtk.STOCK_INFO)
            sound.wave_play('./alert.wav')

        return True

    # 监控按钮
    def monitor_button_clicked(self, button):
        if self.monitor_button_onoff == 0:
            self.monitor_button_onoff = 1
            button.set_label('监 控 中')
            self.monitor_menu_label = "监控中"
            self.alert_list[:] = []

            # 重置单元格字体色彩为黑色
            treeiter = self.liststore.get_iter_first()
            while treeiter != None:
                self.liststore.set_value(treeiter, 6, 'black')
                self.liststore.set_value(treeiter, 7, 'black')
                treeiter = self.liststore.iter_next(treeiter)
            self.progress_timeout()
            self.timer = GObject.timeout_add(self.monitor_time, self.progress_timeout)
        else:
            self.monitor_button_onoff = 0
            button.set_label('未 监 控')
            self.monitor_menu_label = "未监控"
            GObject.source_remove(self.timer)
            self.timer = None

        # 保存到xml文件
        if self.must_save:
            self.save_xml(self.data_file_path + "/gp_data.xml")
            self.must_save = False

        return True

    # hind window
    def hind_window(self, widget, event):
        self.window.set_visible(False)
        return True

    # edit button clicked
    def edit_button_clicked(self, button):
        if self.show_timer != None:
            GObject.source_remove(self.show_timer)
            self.show_timer = None
        editmenu_append = builder.get_object("imagemenuitem8")
        editmenu_delete = builder.get_object("imagemenuitem9")
        editmenu_cancel = builder.get_object("menuitem8")
        viewmenu_first_column = builder.get_object("menuitem9")
        if self.edit_save == False:
            self.edit_save = True
            self.monitor_button.set_sensitive(False)

            # enable drag and drop
            self.treeview.enable_model_drag_source(Gdk.ModifierType.BUTTON1_MASK, self.TARGETS,
                                                   Gdk.DragAction.DEFAULT | Gdk.DragAction.MOVE)
            self.treeview.enable_model_drag_dest(self.TARGETS, Gdk.DragAction.DEFAULT)

            self.col1.set_visible(True)
            viewmenu_first_column.set_active(True)
            self.cell2.set_property('editable', True)
            self.cell4.set_property('editable', True)
            self.cell5.set_property('editable', True)
            self.noteview.set_property('editable', True)
            self.noteview.set_property('cursor-visible', True)

            #是否有已经选中的条目，没有的话默认选中第一条
            selection = self.treeview.get_selection()
            model, treeiter = selection.get_selected()
            if treeiter == None:
                selection.select_path((0,))

            # 编辑菜单
            editmenu_append.set_sensitive(True)
            editmenu_delete.set_sensitive(True)
            editmenu_cancel.set_sensitive(True)


            self.window.set_focus(self.treeview)

            self.edit_button.set_label("保 存")
            # 停止监控
            if self.monitor_button_onoff == 1:
                self.monitor_button_onoff = 0
                self.monitor_button.set_label('未 监 控')
                GObject.source_remove(self.timer)
                self.timer = None
        else:
            self.edit_save = False
            if self.must_save:
                self.save_xml(self.data_file_path + "/gp_data.xml")
                self.must_save = False
            self.edit_button.set_label("编 辑")
            self.cell1.set_property('editable', False)
            self.cell2.set_property('editable', False)
            self.cell4.set_property('editable', False)
            self.cell5.set_property('editable', False)
            self.noteview.set_property('editable', False)
            self.noteview.set_property('cursor-visible', False)
            editmenu_append.set_sensitive(False)
            editmenu_delete.set_sensitive(False)
            editmenu_cancel.set_sensitive(False)
            self.monitor_button.set_sensitive(True)
            self.col1.set_visible(self.ori_visible)
            #设置查看菜单“第一列”勾选框
            viewmenu_first_column.set_active(False)
            self.treeview.unset_rows_drag_source()
            self.treeview.unset_rows_drag_dest()

            self.window.resize(600, 300)

        return

    def button_d_clicked(self, button):
        file = "pictures/" + self.current_gp_code + "/d.jpg"
        os.system("eog " + file)
        return True

    def button_30f_clicked(self, button):
        file = "pictures/" + self.current_gp_code + "/30f.jpg"
        os.system("eog " + file)
        return True

    def button_5f_clicked(self, button):
        file = "pictures/" + self.current_gp_code + "/5f.jpg"
        os.system("eog " + file)
        return True

    def dialog_button_clicked(self, button):
        self.dw.destroy()
        return True

    # cell edited
    def cell_edited(self, cell, path, new_text, column):
        self.must_save = True
        self.alert_list = []
        treeiter = self.liststore.get_iter(path)

        # code列处理
        if column == 1:
            if new_text == '':
                self.show_message('code can not be None, enter again !')
                return
            else:
                df = ts.get_realtime_quotes(new_text)
                self.liststore.set_value(treeiter, 0, df['name'][0])
        # upto列
        if column == 3:
            self.liststore.set_value(treeiter, 6, "black")

        # downto列
        if column == 4:
            self.liststore.set_value(treeiter, 7, "black")
        self.liststore.set_value(treeiter, column, new_text)
        return

    def cell_editing_started(self, cell, editable, path):
        # 先停止监控
        if self.timer == None:
            return
        GObject.source_remove(self.timer)
        self.timer = None
        self.monitor_button.set_label('未 监 控')
        self.monitor_button_onoff = 0
        return

    # 托盘图标及弹出菜单
    def statusicon_button_pressed(self, statusicon, event):
        self.statusicon.set_from_stock(Gtk.STOCK_HOME)
        if event.button == 3:
            return False
        if event.button == 1:
            self.app_window.set_visible(True)
            return True

    def statusicon_popup_menu(self, icon, button, time):
        self.menu = Gtk.Menu()
        show = Gtk.MenuItem()
        show.set_label("显 示")
        show.connect("activate", self.show_window_from_menu_activated)
        self.menu.append(show)

        monitor = Gtk.MenuItem()
        monitor.set_label(self.monitor_menu_label)
        monitor.connect("activate", self.monitor_from_menu)
        self.menu.append(monitor)

        quit = Gtk.MenuItem()
        quit.set_label("退 出")
        quit.connect("activate", Gtk.main_quit)
        self.menu.append(quit)

        self.menu.show_all()
        self.menu.popup(None, None, None, icon, button, time)
        return True

    # 弹出菜单"显示"
    def show_window_from_menu_activated(self, widget):
        self.window.set_visible(True)
        return True

    # 弹出菜单”监控“
    def monitor_from_menu(self, widget):
        self.monitor_button_clicked(self.monitor_button)
        return True

    # 拖拽
    def drag_data_get_data(self, treeview, context, selection, target_id, etime):
        treeselection = treeview.get_selection()
        model, treeiter = treeselection.get_selected()
        # data = model.get_value(treeiter, 0)
        datatuple = model[treeiter][:]
        data = ''
        for item in datatuple:
            if type(item) == bool:
                item = str(item)
            data = data + item + ','
        data = data[:len(data) - 1]
        selection.set(selection.get_target(), 8, data)

    def drag_data_received_data(self, treeview, context, x, y, selection, info, etime):
        model = treeview.get_model()
        data = selection.get_data()
        data_list = data.split(',')
        if data_list[-1] == "True":
            data_list[-1] = True
        if data_list[-1] == "False":
            data_list[-1] = False
        drop_info = treeview.get_dest_row_at_pos(x, y)
        if drop_info:
            path, position = drop_info
            treeiter = model.get_iter(path)
            if (position == Gtk.TreeViewDropPosition.BEFORE or position == Gtk.TreeViewDropPosition.INTO_OR_BEFORE):
                model.insert_before(treeiter, data_list)
            else:
                model.insert_after(treeiter, data_list)
        else:
            model.append(data_list)
        if context.get_selected_action() == Gdk.DragAction.MOVE:
            context.finish(True, True, etime)
        self.must_save = True
        return

    def noteview_changed(self, buffer):
        if self.edit_save:
            self.must_save = True
            selection = self.treeview.get_selection()
            model, treeiter = selection.get_selected()
            text = buffer.get_text(buffer.get_start_iter(), buffer.get_end_iter(), True)
            model[treeiter][5] = text
        return True

    # selection changed
    def treeselection_changed(self, selection):
        model, treeiter = selection.get_selected()
        # 显示个股提示
        if treeiter != None:
            #检查当前股票的图片文件是否存在
            self.current_gp_code = model[treeiter][1]
            #检查存放股票图片的文件夹是否存在，文件夹用股票代码命名
            if not os.path.exists("pictures/" + self.current_gp_code):
                os.mkdir("pictures/" + self.current_gp_code)

            button_d = builder.get_object("button6")
            button_30f = builder.get_object("button7")
            button_5f = builder.get_object("button8")
            button_d.set_sensitive(os.path.isfile("pictures/" + self.current_gp_code +"/d.jpg"))
            button_30f.set_sensitive(os.path.isfile("pictures/" + self.current_gp_code +"/30f.jpg"))
            button_5f.set_sensitive(os.path.isfile("pictures/" + self.current_gp_code +"/5f.jpg"))

            noteview_buffer = self.noteview.get_buffer()
            noteview_buffer.set_text(model[treeiter][5])
        return True

    """------------------------------------------------主菜单事件—start-------------------------------------------"""
    #打开分析窗口
    def windowmenu_fenxi_activated(self, widget):
        op_builder = Gtk.Builder()
        op_builder.add_from_file("./op_window.glade")
        op = op_window.OPERATION(op_builder, "fenxi",None, self.data_file_path)

    # 编辑菜单->添加
    def editmenu_append_activated(self, widget):
        self.col1.set_visible(True)
        self.liststore.append(["新建行", "", "", "", "", "", "black", "black"])
        self.must_save = True
        return True

    # 编辑菜单->删除
    def editmenu_delete_activated(self, widget):
        selection = self.treeview.get_selection()
        model, treeiter = selection.get_selected()
        model.remove(treeiter)
        self.must_save = True
        return True

    # 编辑菜单->撤销，不保存，重新读取xml文件
    def editmenu_cancel_activated(self, item):
        gp_data = gp_xml.read_xml(self.data_file_path + "/gp_data.xml")
        self.liststore.clear()
        for data in gp_data:
            self.liststore.append([data[0], data[1], "", data[2], data[3], data[4], 'black', 'black'])
        self.must_save = False
        return True

    # 查看菜单->日志
    def viewmenu_log_activated(self, widget):
        mw_pos = self.window.get_position()
        mw_size = self.window.get_size()
        app_pos = mw_pos[0] + mw_size[0], mw_pos[1]
        self.app_window.move(app_pos[0] + 10, app_pos[1])
        app_pos = self.app_window.get_position()
        # self.app_window.show_all()
        if not self.app_window.get_visible():
            self.app_window.set_visible(True)
        return True

    def viewmenu_first_column_toggled(self, item):
        if item.get_active():
            self.col1.set_visible(True)
        else:
            self.col1.set_visible(False)
            self.window.resize(600, 300)
        return True

    def treeview_popmenu_hy_activated(self, item):
        selection = self.treeview.get_selection()
        model, self.current_iter = selection.get_selected()
        self.ori_hy = model[self.current_iter][8]
        self.hy_window_code = builder.get_object("entry1")
        self.hy_window_name = builder.get_object("entry2")
        self.hy_window_date = builder.get_object("entry3")
        self.hy_window_info = builder.get_object("textview3")
        self.hy_window_info_buffer = self.hy_window_info.get_buffer()

        #读取fenxi.xml
        self.zhunze, self.zhishus = fenxi_xml.read_xml(self.data_file_path + "/fenxi.xml")

        self.zhunze = self.zhunze.encode('utf8')
        for zhishu in iter(self.zhishus):
            self.zhishus[zhishu][1] = self.zhishus[zhishu][1].encode("utf8")
            self.zhishus[zhishu][4] = self.zhishus[zhishu][4].encode("utf8")

        if self.ori_hy != "": #hy_info显示到窗口
            if self.ori_hy in self.zhishus:
                self.hy_window_code.set_text(self.zhishus[self.ori_hy][0])
                self.hy_window_name.set_text(self.zhishus[self.ori_hy][1])
                self.hy_window_date.set_text(self.zhishus[self.ori_hy][2])
                self.hy_window_info_buffer.set_text(self.zhishus[self.ori_hy][4])
            else:
                self.hy_window_code.set_text(self.ori_hy)
                self.hy_window_info_buffer.set_text("该指数目前没有进行分析！")

        self.hy_window.show_all()
        return True

    """------------------------------------------------主菜单事件—end-------------------------------------------"""

    # treeview删除按钮处理
    def treeview2_key_pressed(self, widget, event):
        if self.edit_save == False:
            return True
        keycode = event.get_keycode()[1]

        # insert按钮添加新行
        if keycode == 118:
            self.col1.set_visible(True)
            self.liststore.append(["新建行", "", "", "", "", "", "black", "black"])
            self.must_save = True

        # delete
        if keycode == 119:
            selection = self.treeview.get_selection()
            model, treeiter = selection.get_selected()
            model.remove(treeiter)
            self.must_save = True
        return True

    """-----------------treeview2右键弹出菜单-start--------------"""

    # treeview2右键弹出菜单
    def treeview2_button_preesed(self, widget, event):
        if event.button == 3:
            selection = self.treeview.get_selection()
            model, treeiter = selection.get_selected()
            op_menu = builder.get_object('menu4')
            op_menu.show_all()
            op_menu.popup(None, None, None, None, event.button, event.get_time())
            return False
        else:
            return False

    def treeview_popmenu_buy_activated(self, widget):
        selection = self.treeview.get_selection()
        model, treeiter = selection.get_selected()
        op_builder = Gtk.Builder()
        op_builder.add_from_file("./op_window.glade")
        op = op_window.OPERATION(op_builder, "buy",{"code": model[treeiter][1], "name": model[treeiter][0], "hy": model[treeiter][8]}, self.data_file_path)

        return True

    def treeview_popmenu_sell_activated(self, widget):
        selection = self.treeview.get_selection()
        model, treeiter = selection.get_selected()
        op_builder = Gtk.Builder()
        op_builder.add_from_file("./op_window.glade")
        op = op_window.OPERATION(op_builder, "sell",{"code": model[treeiter][1], "name": model[treeiter][0], "hy": model[treeiter][8]}, self.data_file_path)
        return True
    """-----------------treeview2右键弹出菜单-end--------------"""

    # applicationwindow
    def applicationwindow1_delete(self, widget, event):
        self.app_window.set_visible(False)
        return True

    def clearall_button_clicked(self, button):
        textbuffer = self.textview.get_buffer()
        textbuffer.set_text("")
        return True

    # save to xml
    def save_xml(self, filename):
        treeiter = self.liststore.get_iter_first()
        gp_data = []
        while treeiter != None:
            gp_data.append([self.liststore.get_value(treeiter, 0), self.liststore.get_value(treeiter, 1),
                            self.liststore.get_value(treeiter, 3), self.liststore.get_value(treeiter, 4),
                            self.liststore.get_value(treeiter, 5), self.liststore.get_value(treeiter, 8)])
            treeiter = self.liststore.iter_next(treeiter)
        gp_xml.write_xml(filename, gp_data)
        return

    # message box
    def show_message(self, text):
        message = Gtk.MessageDialog(self.window, 0, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, text)
        # message.set_size_request(300,100)
        message.run()
        message.destroy()

    def show_notify(self, text):
        if self.nt == None:
            Notify.init("GP alert")
            self.nt = Notify.Notification.new('Alert! Alert! Alert!', text, 'dialog-information')
            self.nt.set_urgency(2)
            self.nt.show()
        return


if __name__ == "__main__":
    builder = Gtk.Builder()
    builder.add_from_file("./gp.glade")
    gp = GP(builder)
    Gtk.main()