2020년 8월 17일 월요일

[IronPython] WPF Layout - Grid

1. WPF Layout - Grid

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")

from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Media.Effects import *

def GetButton(title,size,handler):
    l = Button()
    l.Content = title
    l.FontSize = size
    l.Margin  = Thickness(5)
    l.Padding = Thickness(5)
    l.HorizontalAlignment = HorizontalAlignment.Center;
    l.VerticalAlignment = VerticalAlignment.Center;
    l.Click += ClickEvent
    return l

def ClickEvent(sender,args):
    MessageBox.Show(sender.Content,"Alert")

def GetGrid(row,col):
    g = Grid()
    #g.Width = 320
    #g.Height = 240
    g.HorizontalAlignment = HorizontalAlignment.Stretch
    g.VerticalAlignment = VerticalAlignment.Stretch
    g.ShowGridLines = True
    for c in range(col):
        g.ColumnDefinitions.Add(ColumnDefinition())
    for r in range(row):
        g.RowDefinitions.Add(RowDefinition())
    return g
    
if __name__ == "__main__":     
    w = Window()
    w.Title = "Hello World"
    w.Width = 320
    w.Height = 240
    g = GetGrid(3,4)
    for r in range(3):
        for c in range(4):
            b = GetButton(str(r) + str(c), 16, ClickEvent)
            g.SetRow(b,r)
            g.SetColumn(b,c)
            g.Children.Add(b)
    w.Content = g
    Application().Run(w)  


2. WPF Layout - Grid Span

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")

from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Media.Effects import *

def GetButton(title,size,handler):
    l = Button()
    l.Content = title
    l.FontSize = size
    l.Margin  = Thickness(5)
    l.Padding = Thickness(5)
    l.HorizontalAlignment = HorizontalAlignment.Stretch;
    l.VerticalAlignment = VerticalAlignment.Stretch;
    l.Click += ClickEvent
    return l

def ClickEvent(sender,args):
    MessageBox.Show(sender.Content,"Alert")

def GetGrid(row,col):
    g = Grid()
    #g.Width = 320
    #g.Height = 240
    g.HorizontalAlignment = HorizontalAlignment.Stretch
    g.VerticalAlignment = VerticalAlignment.Stretch
    g.ShowGridLines = False
    for c in range(col):
        g.ColumnDefinitions.Add(ColumnDefinition())
    for r in range(row):
        g.RowDefinitions.Add(RowDefinition())
    return g
    
if __name__ == "__main__":     
    w = Window()
    w.Title = "Hello World"
    w.Width = 320
    w.Height = 240
    g = GetGrid(3,4)
    for r in range(3):
        for c in range(4):
            b = GetButton(str(r) + str(c), 16, ClickEvent)
            g.SetRow(b,r)
            g.SetColumn(b,c)
            if r == 0 and c == 0: 
                g.SetColumnSpan(b,4)
                g.Children.Add(b)
                break
            else:
                g.Children.Add(b)
            
    w.Content = g
    Application().Run(w)    



3. WPF Layout - Grid Column/Row Definition

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")

from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Media.Effects import *

def GetButton(title,size,handler):
    l = Button()
    l.Content = title
    l.FontSize = size
    l.Margin  = Thickness(5)
    l.Padding = Thickness(5)
    l.HorizontalAlignment = HorizontalAlignment.Stretch;
    l.VerticalAlignment = VerticalAlignment.Stretch;
    l.Click += ClickEvent
    return l

def ClickEvent(sender,args):
    MessageBox.Show(sender.Content,"Alert")

def GetGrid(row,col):
    g = Grid()
    g.HorizontalAlignment = HorizontalAlignment.Stretch
    g.VerticalAlignment = VerticalAlignment.Stretch
    g.ShowGridLines = False
    return g

if __name__ == "__main__":     
    w = Window()
    w.Title = "Hello World"
    w.Width = 320
    w.Height = 240
    g = GetGrid(2,3)
    g.ColumnDefinitions.Add(ColumnDefinition(Width=GridLength(60)))
    g.ColumnDefinitions.Add(ColumnDefinition(Width=GridLength(1,GridUnitType.Star)))
    g.ColumnDefinitions.Add(ColumnDefinition(Width=GridLength(60)))
    g.RowDefinitions.Add(RowDefinition(Height=GridLength(1,GridUnitType.Auto)))
    g.RowDefinitions.Add(RowDefinition(Height=GridLength(1,GridUnitType.Star)))
    
    b = GetButton("00", 16, ClickEvent)
    g.SetRow(b,0)
    g.SetColumn(b,0)
    g.Children.Add(b)
    
    b = GetButton("01", 16, ClickEvent)
    g.SetRow(b,0)
    g.SetColumn(b,1)
    g.Children.Add(b)
    
    b = GetButton("02", 16, ClickEvent)
    g.SetRow(b,0)
    g.SetColumn(b,2)
    g.Children.Add(b)
    
    b = GetButton("10", 16, ClickEvent)
    g.SetRow(b,1)
    g.SetColumn(b,0)
    g.SetColumnSpan(b,3)
    g.Children.Add(b)
    
    w.Content = g
    Application().Run(w)      








[IronPython] WPF Control - Button

 1. WPF Control Button

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")

from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Media.Effects import *

def GetToolTip(title):
    tip = ToolTip()
    tip.Content = title
    return tip
    
def GetButton(title,size,handler):
    l = Button()
    l.Content = title
    l.FontSize = size
    l.Margin  = Thickness(5)
    l.Padding = Thickness(5)
    l.HorizontalAlignment = HorizontalAlignment.Center;
    l.VerticalAlignment = VerticalAlignment.Center;
    l.BitmapEffect = DropShadowBitmapEffect()
    l.ToolTip = GetToolTip(title)
    l.Click += ClickEvent
    return l

def ClickEvent(sender,args):
    MessageBox.Show("Label Clicked","Alert")
    
if __name__ == "__main__":     
    w = Window()
    w.Title = "Hello World"
    w.Width = 320
    w.Height = 240
    w.Content = GetButton("Hello World",30,ClickEvent)
    Application().Run(w)   




[IronPython] WPF Controls - Label

 1. WPF Controls Label

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")

from System.Windows import *
from System.Windows.Controls import *
from System.Windows.Media.Effects import *

def GetToolTip(title):
    tip = ToolTip()
    tip.Content = title
    return tip
    
def GetLabel(title,size):
    l = Label()
    l.Content = title
    l.FontSize = size
    l.Margin  = Thickness(5)
    l.Padding = Thickness(5)
    l.HorizontalAlignment = HorizontalAlignment.Center;
    l.VerticalAlignment = VerticalAlignment.Center;
    l.BitmapEffect = DropShadowBitmapEffect()
    l.ToolTip = GetToolTip(title)
    return l
    
if __name__ == "__main__":     
    w = Window()
    w.Title = "Hello World"
    w.Width = 320
    w.Height = 240
    w.Content = GetLabel("Hello World",30)
    Application().Run(w)    





[Iron Python] WPF Window Create

 1. WPF WIndow Create

import clr
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")

from System.Windows import *

if __name__ == "__main__":     
    w = Window()
    w.Title = "Hello World"
    w.Width = 320
    w.Height = 240
    Application().Run(w)    


2020년 8월 12일 수요일

[IronPython] Unzip with Ionic.Zip

 1. Unzip with Ionic.Zip and zipfile

# -*- coding: utf-8 -*-

import clr
#clr.AddReferenceToFileAndPath("DotNetZip")
clr.AddReferenceToFileAndPath("Ionic.Zip")
import Ionic.Zip
#import Ionic.Zip.ZipFile
from Ionic.Zip import *

import zipfile


class UnZip():
    def __init__(self,filename):
        self.zf = Ionic.Zip.ZipFile.Read(filename)
    def print_list(self):
        for z in self.zf:
            print(z.FileName.encode('cp437').decode('cp949'))
    def extract_all(self,folder):
        self.zf.ExtractAll(folder,ExtractExistingFileAction.OverwriteSilently)
    def extract(self,folder,filename):
        self.zf.ExtractSelectedEntries(filename.encode('cp949').decode('cp437'),"",folder,ExtractExistingFileAction.OverwriteSilently)
        #entry file, entry folder, out folder, flag
    def extract2(self,folder,filename):
        for z in self.zf:
            if z.FileName == filename:
                z.Extract(folder,ExtractExistingFileAction.OverwriteSilently)

class PyUnZip():
    def __init__(self,filename):
        self.zf = zipfile.ZipFile(filename)
    def print_list(self):
        for z in self.zf.infolist():
            print(z.filename.decode('cp949'))
    def namelist(self):
        return self.zf.namelist()
    def list(self):
        #zp_info.filename)
        #zp_info.file_size)
        #zp_info.date_time)
        #zp_info.compress_size)
        #zp_info.comment)
        f = []
        for z in self.zf.infolist():
            f.append(z.filename.decode('cp949'))
        return f
    def read(self,filename):
        with self.zf.open(filename.encode("cp949")) as f:
            return f.read()

if __name__ == "__main__":
    uz = UnZip("D:/image.zip")
    uz.print_list()
    uz.extract_all("D:/Temp")
    #uz.extract("D:/Temp","데스크 탑.png")
    #uz.extract2("D:/Temp","Lenna.png")

    pz = PyUnZip("D:/image.zip")
    pz.print_list()
    with open("D:/bbbb.png","wb") as w:
        w.write(pz.read("데스크 탑.png"))

2. ezWebToon
import clr
clr.AddReference('StdLib')
import os
import zipfile
import ezPyWpfLib as ez    

def refreshTree(basedir="webtoon"):
    tree = ez.GetControl('tree')
    dirs = os.listdir(basedir)
    for d in dirs:
        dpath = os.path.join(basedir,d)
        if os.path.isdir(dpath):
            item = tree.AddRootItem(d)
            files = os.listdir(dpath)
            for f in files:
                fpath = os.path.join(dpath,f)
                if os.path.isfile(fpath):
                    tree.AddItem(f,item)  
        elif zipfile.is_zipfile(dpath):
            item = tree.AddRootItem(d)
            with zipfile.ZipFile(dpath) as zf:
                for info in zf.infolist():
                    if not info.filename.endswith('/'):
                        #tree.AddItem(f,item)
                        tree.AddItem(info.filename.decode("cp949"),item)

def onTreeView(event):
    tree = ez.GetControl('tree')
    if tree.IsRootItem(tree.GetSelectedItem()):
        return
    path = tree.GetItemPath(tree.GetParentItem(tree.GetSelectedItem()))    
    if path and zipfile.is_zipfile(path):
        with zipfile.ZipFile(path) as zf:
            with zf.open(tree.GetSelectedItemText().encode("cp949")) as f:
                web = ez.GetControl('web')
                web.Load(f.read())
    else:
        path = tree.GetSelectedItemPath()   
        if os.path.isfile(path) and path.endswith("html"):
            with open(path) as f:
                web = ez.GetControl('web')
                web.Load(f.read())   

def onCreated():
    ez.DumpControlTable()
    refreshTree()

def onClosing(event):
    if not ez.YesNoDialog("Do you want to quie ?","Quit"):
        event.args.Cancel = True

split1 = [[ { "name" : "TreeView", "label" : "WebToon", "key" : "tree", 'handler' : onTreeView, 'fontsize':14, "expand" : True },
          { "expand" : True }, ]]
split2 = [[ { "name" : "WebView", "key" : "web", "expand" : True, "toolbar" : False, "uri" : "http://google.co.kr" },   
        { "expand" : True }, ]]

app_content = [ # vbox  
    [ # hbox
        { "name" : "HSplit", "items" : [ split1, split2 ] , "first" : 0.4, "expand" : True, 'border' : False},
        { "expand" : True, 'border' : True  },
    ],          
]

def MakeWindow():
    win = ez.Window()
    win.SetTitle("WebToon Viewer")
    win.SetSize(640,400)
    win.SetContent(app_content)
    win.SetCreatedHandler(onCreated)  
    win.SetCloseHandler(onClosing)
    return win

if __name__ == "__main__":
    global appWin
    appWin = MakeWindow()
    appWin.Run()

[IronPython] WebCrawling with NSoup

 1. WolfCom example

import os
import clr
clr.AddReferenceToFileAndPath("NSoup")
import NSoup

import System
from System.IO import *
from System.Net import *

debug = False
image_ext = None

if __name__ == "__main__":
    url = "https://wfwf104.com/list?toon=1229"
    baseUrl = "https://wfwf104.com"
    baseDir = r"D:\Temp3"
    doc = NSoup.NSoupClient.Connect(url).Get()
    '''
    with open("a.html", "w") as f:
        f.write(document.Html())
    '''
    elems = doc.Select("div.box > div.group.left-box > div.webtoon-bbs-list.bbs-list > ul > li");
    if debug:
        print(elems.Html());
        
    print(doc.Title)
    new_dir = os.path.join(baseDir, doc.Title.replace(":","_"))
    if not os.path.isdir(new_dir): os.mkdir(new_dir)
    print(new_dir)
    
    for e in elems:
        url = e.Select("a").First.Attr("href")
        if not url: continue
        url = baseUrl + url

        doc = NSoup.NSoupClient.Connect(url).Get()
        imgs = doc.Select("section.webtoon-body > div.group.image-view > img");
        print(doc.Title)

        sub_dir = os.path.join(new_dir, doc.Title.replace(":","_"))
        if not os.path.isdir(sub_dir): os.mkdir(sub_dir)

        k = 1;
        for img in imgs:
            img_url = img.Attr('src')
            if not img_url: continue
            if image_ext == None or img_url.endswith(image_ext):
                if( not img_url.startswith("http") ):
                    img_url = baseUrl + img_url
                file_name = "img_%04d.jpg" % k
                WebClient().DownloadFile(img_url, os.path.join( sub_dir, file_name))
                print( img_url + " -> " + file_name )
                k = k + 1


    
    
    
    

2020년 8월 10일 월요일

[IronPython] How to embed standard library

1. make StdLib.py

import glob
import subprocess
#...
#Build StdLib.DLL
ipath = r'c:\Bin\IronPython2.7'
ipyc = ipath + r'\ipyc.exe'
# any library files you need
gb = []
gb += glob.glob( ipath + r".\Lib\*.py")
gb += glob.glob( ipath + r".\Lib\encodings\*.py")
# ...
gb = [ipyc,"/main:StdLib.py","/embed","/platform:x86","/target:dll"] + gb
subprocess.call(gb)
print (gb)
print ("Made StdLib")

2. make Application with StdLib.dll

'''
import os
import zipfile
try:
    import ezPyWpfLib as ez    
except:
    import ezPyJFxLib as ez
'''
import clr
clr.AddReference("StdLib")
clr.AddReferenceToFileAndPath("ezPyWpfLib.dll")
import ezPyWpfLib as ez
import os
import zipfile

def refreshTree(basedir="webtoon"):
    tree = ez.GetControl('tree')
    dirs = os.listdir(basedir)
    for d in dirs:
        dpath = os.path.join(basedir,d)
        if os.path.isdir(dpath):
            item = tree.AddRootItem(d)
            files = os.listdir(dpath)
            for f in files:
                fpath = os.path.join(dpath,f)
                if os.path.isfile(fpath):
                    tree.AddItem(f,item)  
        elif zipfile.is_zipfile(dpath):
            item = tree.AddRootItem(d)
            with zipfile.ZipFile(dpath) as zf:
                for info in zf.infolist():
                    if not info.filename.endswith('/'):
                        #tree.AddItem(f,item)
                        tree.AddItem(info.filename.decode("cp949"),item)

def onTreeView(event):
    tree = ez.GetControl('tree')
    if tree.IsRootItem(tree.GetSelectedItem()):
        return
    path = tree.GetItemPath(tree.GetParentItem(tree.GetSelectedItem()))    
    if path and zipfile.is_zipfile(path):
        with zipfile.ZipFile(path) as zf:
            with zf.open(tree.GetSelectedItemText().encode("cp949")) as f:
                web = ez.GetControl('web')
                web.Load(f.read())
    else:
        path = tree.GetSelectedItemPath()   
        if os.path.isfile(path) and path.endswith("html"):
            with open(path) as f:
                web = ez.GetControl('web')
                web.Load(f.read())   

def onCreated():
    ez.DumpControlTable()
    refreshTree()

def onClosing(event):
    if not ez.YesNoDialog("Do you want to quie ?","Quit"):
        event.args.Cancel = True

split1 = [[ { "name" : "TreeView", "label" : "WebToon", "key" : "tree", 'handler' : onTreeView,"expand" : True },
          { "expand" : True }, ]]
split2 = [[ { "name" : "WebView", "key" : "web", "expand" : True, "toolbar" : False, "uri" : "http://google.co.kr" },   
        { "expand" : True }, ]]

app_content = [ # vbox  
    [ # hbox
        { "name" : "HSplit", "items" : [ split1, split2 ] , "first" : 0.2, "expand" : True, 'border' : False},
        { "expand" : True, 'border' : True  },
    ],          
]

def MakeWindow():
    win = ez.Window()
    win.SetTitle("WebToon Viewer")
    win.SetSize(640,400)
    win.SetContent(app_content)
    win.SetCreatedHandler(onCreated)  
    win.SetCloseHandler(onClosing)
    return win

if __name__ == "__main__":
    global appWin
    appWin = MakeWindow()
    appWin.Run()

2020년 8월 6일 목요일

wxPython App Example II

1. wxPython App Example


import os
import time
import wx
import wx.xrc
import wx_gui as w

def runLater(handler):
	wx.CallAfter(handler)

def runThread(handler):
	import threading
	thread = threading.Thread(target=handler)
	thread.start()

class FileDrop(wx.FileDropTarget):
	def __init__(self, window):
		wx.FileDropTarget.__init__(self)
		self.window = window
	def OnDropFiles(self, x, y, filenames):
		self.window.OnDropFile(filenames)
		return True

class Timer():
	def __init__(self,parent,handler):
		self.timer = wx.Timer(parent)
		parent.Bind( wx.EVT_TIMER, handler, self.timer )
	def start(self,msec):
		self.timer.Start(msec)
	def stop(self):
		self.timer.Stop()
		
class Frame(w.Frame):
	def __init__(self):
		w.Frame.__init__(self,None)
		self.SetFileDropHandler()
		self.SetTimerHandler()
		self.SetListColumn( 
			("File Name", "Size", "Status"), 
			( 360, 80, 80 ),
			( -1, 1, wx.LIST_FORMAT_CENTER ) )
		self.timerCount = 0
		self.threadCount = 0
		
	def SetFileDropHandler(self):
		dropTarget = FileDrop(self)
		self.m_textFile.SetDropTarget(dropTarget)
		self.m_listData.SetDropTarget(dropTarget)

	def SetTimerHandler(self):
		self.timer = Timer( self, self.TimerHandler )
		
	def TimerHandler(self,event):
		self.m_statusBar.SetStatusText( " " + str(self.timerCount), 0 )
		self.timerCount = self.timerCount + 1
		
	def ThreadAction(self):
		self.m_statusBar.SetStatusText( " " + str(self.threadCount), 1 )
		self.threadCount = self.threadCount + 1
		
	def ThreadHandler(self):
		for i in range(100):
			runLater(self.ThreadAction)
			time.sleep(0.5)
		
	def SetListColumn(self,labels,widths,aligns):
		for i in range(len(labels)):
			self.m_listData.AppendColumn( labels[i], format=aligns[i], width=widths[i] )
			
	def AddListRow(self,row):
		self.m_listData.Append( row )
	
	def OnDropFile(self,filenames):
		for f in filenames:		
			if os.path.isfile(f):
				self.AddListRow( (f, os.path.getsize(f), "-") )

	def m_buttonStartOnButtonClick( self, event ):
		self.timer.start(1000)
		runThread(self.ThreadHandler)
		event.Skip()

	def m_buttonStopOnButtonClick( self, event ):
		self.timer.stop()
		event.Skip()

class App(wx.App):
    def OnInit(self):
        frame = Frame()
        frame.Show()
        self.SetTopWindow(frame)
        return True
        
if __name__ == "__main__":
	app = App()
	app.MainLoop()

2020년 8월 2일 일요일

[ezGuiLib] ZipWebToon Viewer

1. ZipWebToon Viewer


import os
import zipfile
try:
    import ezPyWpfLib as ez    
except:
    import ezPyJFxLib as ez
'''
import clr
clr.AddReferenceToFileAndPath("ezPyWpfLib.dll")
import ezPyWpfLib as ez
'''

def refreshTree(basedir="webtoon"):
    tree = ez.GetControl('tree')
    dirs = os.listdir(basedir)
    for d in dirs:
        dpath = os.path.join(basedir,d)
        if os.path.isdir(dpath):
            item = tree.AddRootItem(d)
            files = os.listdir(dpath)
            for f in files:
                fpath = os.path.join(dpath,f)
                if os.path.isfile(fpath):
                    tree.AddItem(f,item)  
        elif zipfile.is_zipfile(dpath):
            item = tree.AddRootItem(d)
            with zipfile.ZipFile(dpath) as zf:
                for f in zf.namelist():
                    if not f.endswith('/'):
                        tree.AddItem(f,item)

def onTreeView(event):
    tree = ez.GetControl('tree')
    path = tree.GetItemPath(tree.GetParentItem(tree.GetSelectedItem()))  
    if zipfile.is_zipfile(path):
        with zipfile.ZipFile(path) as zf:
            with zf.open(tree.GetSelectedItemText()) as f:
                web = ez.GetControl('web')
                web.Load(f.read())
    else:
        path = tree.GetSelectedItemPath()   
        if os.path.isfile(path) and path.endswith("html"):
            with open(path) as f:
                web = ez.GetControl('web')
                web.Load(f.read())   

def onCreated():
    ez.DumpControlTable()
    refreshTree()

def onClosing(event):
    if not ez.YesNoDialog("Do you want to quie ?","Quit"):
        event.args.Cancel = True

split1 = [[ { "name" : "TreeView", "label" : "WebToon", "key" : "tree", 'handler' : onTreeView,"expand" : True },
          { "expand" : True }, ]]
split2 = [[ { "name" : "WebView", "key" : "web", "expand" : True, "toolbar" : False, "uri" : "http://google.co.kr" },   
        { "expand" : True }, ]]

app_content = [ # vbox  
    [ # hbox
        { "name" : "HSplit", "items" : [ split1, split2 ] , "first" : 0.2, "expand" : True, 'border' : False},
        { "expand" : True, 'border' : True  },
    ],          
]

def MakeWindow():
    win = ez.Window()
    win.SetTitle("WebToon Viewer")
    win.SetSize(640,400)
    win.SetContent(app_content)
    win.SetCreatedHandler(onCreated)  
    win.SetCloseHandler(onClosing)
    return win

if __name__ == "__main__":
    global appWin
    appWin = MakeWindow()
    appWin.Run()