FlatCAMApp.py 260 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import re
  17. import os
  18. from stat import S_IREAD, S_IRGRP, S_IROTH
  19. import subprocess
  20. import tkinter as tk
  21. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  22. import time # Just used for debugging. Double check before removing.
  23. import urllib.request, urllib.parse, urllib.error
  24. import webbrowser
  25. from contextlib import contextmanager
  26. from xml.dom.minidom import parseString as parse_xml_string
  27. from copy import copy,deepcopy
  28. import numpy as np
  29. from datetime import datetime
  30. import gc
  31. ########################################
  32. ## Imports part of FlatCAM ##
  33. ########################################
  34. from ObjectCollection import *
  35. from FlatCAMObj import *
  36. from PlotCanvas import *
  37. from FlatCAMGUI import *
  38. from FlatCAMCommon import LoudDict
  39. from FlatCAMPostProc import load_postprocessors
  40. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  41. from FlatCAMProcess import *
  42. from FlatCAMWorkerStack import WorkerStack
  43. from VisPyVisuals import Color
  44. from vispy.gloo.util import _screenshot
  45. from vispy.io import write_png
  46. from flatcamTools import *
  47. from multiprocessing import Pool
  48. import tclCommands
  49. # from ParseFont import *
  50. ########################################
  51. ## App ##
  52. ########################################
  53. class App(QtCore.QObject):
  54. """
  55. The main application class. The constructor starts the GUI.
  56. """
  57. # Get Cmd Line Options
  58. cmd_line_shellfile = ''
  59. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  60. try:
  61. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  62. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  63. except getopt.GetoptError:
  64. print(cmd_line_help)
  65. sys.exit(2)
  66. for opt, arg in cmd_line_options:
  67. if opt == '-h':
  68. print(cmd_line_help)
  69. sys.exit()
  70. elif opt == '--shellfile':
  71. cmd_line_shellfile = arg
  72. # Logging ##
  73. log = logging.getLogger('base')
  74. log.setLevel(logging.DEBUG)
  75. # log.setLevel(logging.WARNING)
  76. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  77. handler = logging.StreamHandler()
  78. handler.setFormatter(formatter)
  79. log.addHandler(handler)
  80. # Version
  81. version = 8.906
  82. version_date = "2019/02/1"
  83. beta = True
  84. # URL for update checks and statistics
  85. version_url = "http://flatcam.org/version"
  86. # App URL
  87. app_url = "http://flatcam.org"
  88. # Manual URL
  89. manual_url = "http://flatcam.org/manual/index.html"
  90. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  91. should_we_quit = True
  92. ##################
  93. ## Signals ##
  94. ##################
  95. # Inform the user
  96. # Handled by:
  97. # * App.info() --> Print on the status bar
  98. inform = QtCore.pyqtSignal(str)
  99. # General purpose background task
  100. worker_task = QtCore.pyqtSignal(dict)
  101. # File opened
  102. # Handled by:
  103. # * register_folder()
  104. # * register_recent()
  105. # Note: Setting the parameters to unicode does not seem
  106. # to have an effect. Then are received as Qstring
  107. # anyway.
  108. # File type and filename
  109. file_opened = QtCore.pyqtSignal(str, str)
  110. # File type and filename
  111. file_saved = QtCore.pyqtSignal(str, str)
  112. # Percentage of progress
  113. progress = QtCore.pyqtSignal(int)
  114. plots_updated = QtCore.pyqtSignal()
  115. # Emitted by new_object() and passes the new object as argument, plot flag.
  116. # on_object_created() adds the object to the collection, plots on appropriate flag
  117. # and emits new_object_available.
  118. object_created = QtCore.pyqtSignal(object, bool, bool)
  119. # Emitted when a object has been changed (like scaled, mirrored)
  120. object_changed = QtCore.pyqtSignal(object)
  121. # Emitted after object has been plotted.
  122. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  123. object_plotted = QtCore.pyqtSignal(object)
  124. # Emitted when a new object has been added to the collection
  125. # and is ready to be used.
  126. new_object_available = QtCore.pyqtSignal(object)
  127. message = QtCore.pyqtSignal(str, str, str)
  128. # Emmited when shell command is finished(one command only)
  129. shell_command_finished = QtCore.pyqtSignal(object)
  130. # Emitted when multiprocess pool has been recreated
  131. pool_recreated = QtCore.pyqtSignal(object)
  132. # Emitted when an unhandled exception happens
  133. # in the worker task.
  134. thread_exception = QtCore.pyqtSignal(object)
  135. def __init__(self, user_defaults=True, post_gui=None):
  136. """
  137. Starts the application.
  138. :return: app
  139. :rtype: App
  140. """
  141. App.log.info("FlatCAM Starting...")
  142. ###################
  143. ### OS-specific ###
  144. ###################
  145. # Folder for user settings.
  146. if sys.platform == 'win32':
  147. from win32com.shell import shell, shellcon
  148. if platform.architecture()[0] == '32bit':
  149. App.log.debug("Win32!")
  150. else:
  151. App.log.debug("Win64!")
  152. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  153. '\FlatCAM'
  154. self.os = 'windows'
  155. else: # Linux/Unix/MacOS
  156. self.data_path = os.path.expanduser('~') + \
  157. '/.FlatCAM'
  158. self.os = 'unix'
  159. ###############################
  160. ### Setup folders and files ###
  161. ###############################
  162. if not os.path.exists(self.data_path):
  163. os.makedirs(self.data_path)
  164. App.log.debug('Created data folder: ' + self.data_path)
  165. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  166. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  167. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  168. if not os.path.exists(self.postprocessorpaths):
  169. os.makedirs(self.postprocessorpaths)
  170. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  171. # create current_defaults.FlatConfig file if there is none
  172. try:
  173. f = open(self.data_path + '/current_defaults.FlatConfig')
  174. f.close()
  175. except IOError:
  176. App.log.debug('Creating empty current_defaults.FlatConfig')
  177. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  178. json.dump({}, f)
  179. f.close()
  180. # create factory_defaults.FlatConfig file if there is none
  181. try:
  182. f = open(self.data_path + '/factory_defaults.FlatConfig')
  183. f.close()
  184. except IOError:
  185. App.log.debug('Creating empty factory_defaults.FlatConfig')
  186. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  187. json.dump({}, f)
  188. f.close()
  189. try:
  190. f = open(self.data_path + '/recent.json')
  191. f.close()
  192. except IOError:
  193. App.log.debug('Creating empty recent.json')
  194. f = open(self.data_path + '/recent.json', 'w')
  195. json.dump([], f)
  196. f.close()
  197. # Application directory. CHDIR to it. Otherwise, trying to load
  198. # GUI icons will fail as their path is relative.
  199. # This will fail under cx_freeze ...
  200. self.app_home = os.path.dirname(os.path.realpath(__file__))
  201. App.log.debug("Application path is " + self.app_home)
  202. App.log.debug("Started in " + os.getcwd())
  203. # cx_freeze workaround
  204. if os.path.isfile(self.app_home):
  205. self.app_home = os.path.dirname(self.app_home)
  206. os.chdir(self.app_home)
  207. # Create multiprocessing pool
  208. self.pool = Pool()
  209. ####################
  210. ## Initialize GUI ##
  211. ####################
  212. # FlatCAM colors used in plotting
  213. self.FC_light_green = '#BBF268BF'
  214. self.FC_dark_green = '#006E20BF'
  215. self.FC_light_blue = '#a5a5ffbf'
  216. self.FC_dark_blue = '#0000ffbf'
  217. QtCore.QObject.__init__(self)
  218. self.ui = FlatCAMGUI(self.version, self.beta, self)
  219. # self.connect(self.ui,
  220. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  221. # self.save_geometry) PyQt4
  222. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  223. self.ui.final_save.connect(self.final_save)
  224. ##############
  225. #### Data ####
  226. ##############
  227. self.recent = []
  228. self.clipboard = QtWidgets.QApplication.clipboard()
  229. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  230. self.project_filename = None
  231. self.toggle_units_ignore = False
  232. # self.defaults_form = PreferencesUI()
  233. self.general_defaults_form = GeneralPreferencesUI()
  234. self.gerber_defaults_form = GerberPreferencesUI()
  235. self.excellon_defaults_form = ExcellonPreferencesUI()
  236. self.geometry_defaults_form = GeometryPreferencesUI()
  237. self.cncjob_defaults_form = CNCJobPreferencesUI()
  238. self.tools_defaults_form = ToolsPreferencesUI()
  239. # when adding entries here read the comments in the method found bellow named:
  240. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  241. self.defaults_form_fields = {
  242. "units": self.general_defaults_form.general_app_group.units_radio,
  243. "global_shell_at_startup": self.general_defaults_form.general_app_group.shell_startup_cb,
  244. "global_version_check": self.general_defaults_form.general_app_group.version_check_cb,
  245. "global_send_stats": self.general_defaults_form.general_app_group.send_stats_cb,
  246. "global_gridx": self.general_defaults_form.general_gui_group.gridx_entry,
  247. "global_gridy": self.general_defaults_form.general_gui_group.gridy_entry,
  248. "global_plot_fill": self.general_defaults_form.general_gui_group.pf_color_entry,
  249. "global_plot_line": self.general_defaults_form.general_gui_group.pl_color_entry,
  250. "global_sel_fill": self.general_defaults_form.general_gui_group.sf_color_entry,
  251. "global_sel_line": self.general_defaults_form.general_gui_group.sl_color_entry,
  252. "global_alt_sel_fill": self.general_defaults_form.general_gui_group.alt_sf_color_entry,
  253. "global_alt_sel_line": self.general_defaults_form.general_gui_group.alt_sl_color_entry,
  254. "global_draw_color": self.general_defaults_form.general_gui_group.draw_color_entry,
  255. "global_sel_draw_color": self.general_defaults_form.general_gui_group.sel_draw_color_entry,
  256. "global_pan_button": self.general_defaults_form.general_app_group.pan_button_radio,
  257. "global_mselect_key": self.general_defaults_form.general_app_group.mselect_radio,
  258. # "global_pan_with_space_key": self.general_defaults_form.general_gui_group.pan_with_space_cb,
  259. "global_workspace": self.general_defaults_form.general_gui_group.workspace_cb,
  260. "global_workspaceT": self.general_defaults_form.general_gui_group.wk_cb,
  261. "gerber_plot": self.gerber_defaults_form.gerber_gen_group.plot_cb,
  262. "gerber_solid": self.gerber_defaults_form.gerber_gen_group.solid_cb,
  263. "gerber_multicolored": self.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  264. "gerber_circle_steps": self.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  265. "gerber_isotooldia": self.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  266. "gerber_isopasses": self.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  267. "gerber_isooverlap": self.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  268. "gerber_combine_passes": self.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  269. "gerber_milling_type": self.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  270. "gerber_noncoppermargin": self.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  271. "gerber_noncopperrounded": self.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  272. "gerber_bboxmargin": self.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  273. "gerber_bboxrounded": self.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  274. "excellon_plot": self.excellon_defaults_form.excellon_gen_group.plot_cb,
  275. "excellon_solid": self.excellon_defaults_form.excellon_gen_group.solid_cb,
  276. "excellon_format_upper_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  277. "excellon_format_lower_in": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  278. "excellon_format_upper_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  279. "excellon_format_lower_mm": self.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  280. "excellon_zeros": self.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  281. "excellon_units": self.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  282. "excellon_optimization_type": self.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  283. "excellon_search_time": self.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  284. "excellon_drillz": self.excellon_defaults_form.excellon_opt_group.cutz_entry,
  285. "excellon_travelz": self.excellon_defaults_form.excellon_opt_group.travelz_entry,
  286. "excellon_feedrate": self.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  287. "excellon_feedrate_rapid": self.excellon_defaults_form.excellon_opt_group.feedrate_rapid_entry,
  288. "excellon_spindlespeed": self.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  289. "excellon_dwell": self.excellon_defaults_form.excellon_opt_group.dwell_cb,
  290. "excellon_dwelltime": self.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  291. "excellon_toolchange": self.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  292. "excellon_toolchangez": self.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  293. "excellon_toolchangexy": self.excellon_defaults_form.excellon_opt_group.toolchangexy_entry,
  294. "excellon_ppname_e": self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  295. "excellon_startz": self.excellon_defaults_form.excellon_opt_group.estartz_entry,
  296. "excellon_endz": self.excellon_defaults_form.excellon_opt_group.eendz_entry,
  297. "excellon_tooldia": self.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  298. "excellon_slot_tooldia": self.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  299. "excellon_gcode_type": self.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  300. "geometry_plot": self.geometry_defaults_form.geometry_gen_group.plot_cb,
  301. "geometry_cnctooldia": self.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  302. "geometry_circle_steps": self.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  303. "geometry_segx": self.geometry_defaults_form.geometry_opt_group.segx_entry,
  304. "geometry_segy": self.geometry_defaults_form.geometry_opt_group.segy_entry,
  305. "geometry_cutz": self.geometry_defaults_form.geometry_opt_group.cutz_entry,
  306. "geometry_travelz": self.geometry_defaults_form.geometry_opt_group.travelz_entry,
  307. "geometry_feedrate": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  308. "geometry_feedrate_z": self.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  309. "geometry_feedrate_rapid": self.geometry_defaults_form.geometry_opt_group.cncfeedrate_rapid_entry,
  310. "geometry_spindlespeed": self.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  311. "geometry_dwell": self.geometry_defaults_form.geometry_opt_group.dwell_cb,
  312. "geometry_dwelltime": self.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  313. "geometry_ppname_g": self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  314. "geometry_toolchange": self.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  315. "geometry_toolchangez": self.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  316. "geometry_toolchangexy": self.geometry_defaults_form.geometry_opt_group.toolchangexy_entry,
  317. "geometry_startz": self.geometry_defaults_form.geometry_opt_group.gstartz_entry,
  318. "geometry_endz": self.geometry_defaults_form.geometry_opt_group.gendz_entry,
  319. "geometry_multidepth": self.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  320. "geometry_depthperpass": self.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  321. "geometry_extracut": self.geometry_defaults_form.geometry_opt_group.extracut_cb,
  322. "cncjob_plot": self.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  323. "cncjob_tooldia": self.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  324. "cncjob_coords_decimals": self.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  325. "cncjob_fr_decimals": self.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  326. "cncjob_steps_per_circle": self.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  327. "cncjob_prepend": self.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  328. "cncjob_append": self.cncjob_defaults_form.cncjob_opt_group.append_text,
  329. "tools_ncctools": self.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  330. "tools_nccoverlap": self.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  331. "tools_nccmargin": self.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  332. "tools_nccmethod": self.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  333. "tools_nccconnect": self.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  334. "tools_ncccontour": self.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  335. "tools_nccrest": self.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  336. "tools_cutouttooldia": self.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  337. "tools_cutoutmargin": self.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  338. "tools_cutoutgapsize": self.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  339. "tools_gaps_rect": self.tools_defaults_form.tools_cutout_group.gaps_radio,
  340. "tools_gaps_ff": self.tools_defaults_form.tools_cutout_group.gaps_combo,
  341. "tools_painttooldia": self.tools_defaults_form.tools_paint_group.painttooldia_entry,
  342. "tools_paintoverlap": self.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  343. "tools_paintmargin": self.tools_defaults_form.tools_paint_group.paintmargin_entry,
  344. "tools_paintmethod": self.tools_defaults_form.tools_paint_group.paintmethod_combo,
  345. "tools_selectmethod": self.tools_defaults_form.tools_paint_group.selectmethod_combo,
  346. "tools_pathconnect": self.tools_defaults_form.tools_paint_group.pathconnect_cb,
  347. "tools_paintcontour": self.tools_defaults_form.tools_paint_group.contour_cb,
  348. "tools_2sided_mirror_axis": self.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  349. "tools_2sided_axis_loc": self.tools_defaults_form.tools_2sided_group.axis_location_radio,
  350. "tools_2sided_drilldia": self.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  351. }
  352. # loads postprocessors
  353. self.postprocessors = load_postprocessors(self)
  354. for name in list(self.postprocessors.keys()):
  355. self.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  356. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  357. if name == 'hpgl':
  358. continue
  359. self.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  360. self.defaults = LoudDict()
  361. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  362. self.defaults.update({
  363. "global_serial": 0,
  364. "global_stats": {},
  365. "units": "IN",
  366. "global_version_check": True,
  367. "global_send_stats": True,
  368. "global_gridx": 1.0,
  369. "global_gridy": 1.0,
  370. "global_plot_fill": '#BBF268BF',
  371. "global_plot_line": '#006E20BF',
  372. "global_sel_fill": '#a5a5ffbf',
  373. "global_sel_line": '#0000ffbf',
  374. "global_alt_sel_fill": '#BBF268BF',
  375. "global_alt_sel_line": '#006E20BF',
  376. "global_draw_color": '#FF0000',
  377. "global_sel_draw_color": '#0000FF',
  378. "global_pan_button": '2',
  379. "global_mselect_key": 'Control',
  380. # "global_pan_with_space_key": False,
  381. "global_workspace": False,
  382. "global_workspaceT": "A4P",
  383. "global_toolbar_view": 31,
  384. "global_background_timeout": 300000, # Default value is 5 minutes
  385. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  386. # (python trace only for unknown errors),
  387. # 1 = show trace(show trace allways),
  388. # 2 = (For the future).
  389. # Persistence
  390. "global_last_folder": None,
  391. "global_last_save_folder": None,
  392. # Default window geometry
  393. "global_def_win_x": 100,
  394. "global_def_win_y": 100,
  395. "global_def_win_w": 1024,
  396. "global_def_win_h": 650,
  397. # Constants...
  398. "global_defaults_save_period_ms": 20000, # Time between default saves.
  399. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  400. "global_shell_at_startup": False, # Show the shell at startup.
  401. "global_recent_limit": 10, # Max. items in recent list.
  402. "fit_key": '1',
  403. "zoom_out_key": '2',
  404. "zoom_in_key": '3',
  405. "grid_toggle_key": 'G',
  406. "zoom_ratio": 1.5,
  407. "global_point_clipboard_format": "(%.4f, %.4f)",
  408. "global_zdownrate": None,
  409. "gerber_plot": True,
  410. "gerber_solid": True,
  411. "gerber_multicolored": False,
  412. "gerber_isotooldia": 0.016,
  413. "gerber_isopasses": 1,
  414. "gerber_isooverlap": 0.15,
  415. "gerber_combine_passes": False,
  416. "gerber_milling_type": "cl",
  417. "gerber_noncoppermargin": 0.1,
  418. "gerber_noncopperrounded": False,
  419. "gerber_bboxmargin": 0.1,
  420. "gerber_bboxrounded": False,
  421. "gerber_circle_steps": 64,
  422. "gerber_use_buffer_for_union": True,
  423. "excellon_plot": True,
  424. "excellon_solid": True,
  425. "excellon_format_upper_in": 2,
  426. "excellon_format_lower_in": 4,
  427. "excellon_format_upper_mm": 3,
  428. "excellon_format_lower_mm": 3,
  429. "excellon_zeros": "L",
  430. "excellon_units": "INCH",
  431. "excellon_optimization_type": 'B',
  432. "excellon_search_time": 3,
  433. "excellon_drillz": -0.1,
  434. "excellon_travelz": 0.1,
  435. "excellon_feedrate": 3.0,
  436. "excellon_feedrate_rapid": 3.0,
  437. "excellon_spindlespeed": None,
  438. "excellon_dwell": False,
  439. "excellon_dwelltime": 1,
  440. "excellon_toolchange": False,
  441. "excellon_toolchangez": 1.0,
  442. "excellon_toolchangexy": "0.0, 0.0",
  443. "excellon_tooldia": 0.016,
  444. "excellon_slot_tooldia": 0.016,
  445. "excellon_startz": None,
  446. "excellon_endz": 2.0,
  447. "excellon_ppname_e": 'default',
  448. "excellon_gcode_type": "drills",
  449. "geometry_plot": True,
  450. "geometry_segx": 0.0,
  451. "geometry_segy": 0.0,
  452. "geometry_cutz": -0.002,
  453. "geometry_travelz": 0.1,
  454. "geometry_toolchange": False,
  455. "geometry_toolchangez": 1.0,
  456. "geometry_toolchangexy": "0.0, 0.0",
  457. "geometry_startz": None,
  458. "geometry_endz": 2.0,
  459. "geometry_feedrate": 3.0,
  460. "geometry_feedrate_z": 3.0,
  461. "geometry_feedrate_rapid": 3.0,
  462. "geometry_cnctooldia": 0.016,
  463. "geometry_spindlespeed": None,
  464. "geometry_dwell": False,
  465. "geometry_dwelltime": 1,
  466. "geometry_ppname_g": 'default',
  467. "geometry_depthperpass": 0.002,
  468. "geometry_multidepth": False,
  469. "geometry_extracut": False,
  470. "geometry_circle_steps": 64,
  471. "cncjob_plot": True,
  472. "cncjob_tooldia": 0.0393701,
  473. "cncjob_coords_decimals": 4,
  474. "cncjob_fr_decimals": 2,
  475. "cncjob_prepend": "",
  476. "cncjob_append": "",
  477. "cncjob_steps_per_circle": 64,
  478. "tools_ncctools": "1.0, 0.5",
  479. "tools_nccoverlap": 0.4,
  480. "tools_nccmargin": 0.1,
  481. "tools_nccmethod": "seed",
  482. "tools_nccconnect": True,
  483. "tools_ncccontour": True,
  484. "tools_nccrest": False,
  485. "tools_cutouttooldia": 0.1,
  486. "tools_cutoutmargin": 0.1,
  487. "tools_cutoutgapsize": 0.15,
  488. "tools_gaps_rect": "4",
  489. "tools_gaps_ff": "8",
  490. "tools_painttooldia": 0.07,
  491. "tools_paintoverlap": 0.15,
  492. "tools_paintmargin": 0.0,
  493. "tools_paintmethod": "seed",
  494. "tools_selectmethod": "single",
  495. "tools_pathconnect": True,
  496. "tools_paintcontour": True,
  497. "tools_2sided_mirror_axis": "X",
  498. "tools_2sided_axis_loc": "point",
  499. "tools_2sided_drilldia": 1,
  500. })
  501. ###############################
  502. ### Load defaults from file ###
  503. if user_defaults:
  504. self.load_defaults(filename='current_defaults')
  505. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  506. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  507. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  508. self.save_defaults(silent=True)
  509. self.propagate_defaults(silent=True)
  510. self.restore_main_win_geom()
  511. def auto_save_defaults():
  512. try:
  513. self.save_defaults(silent=True)
  514. self.propagate_defaults(silent=True)
  515. finally:
  516. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  517. # the following lines activates automatic defaults save
  518. # if user_defaults:
  519. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  520. # self.options_form = PreferencesUI()
  521. self.general_options_form = GeneralPreferencesUI()
  522. self.gerber_options_form = GerberPreferencesUI()
  523. self.excellon_options_form = ExcellonPreferencesUI()
  524. self.geometry_options_form = GeometryPreferencesUI()
  525. self.cncjob_options_form = CNCJobPreferencesUI()
  526. self.tools_options_form = ToolsPreferencesUI()
  527. self.options_form_fields = {
  528. "units": self.general_options_form.general_app_group.units_radio,
  529. "global_gridx": self.general_options_form.general_gui_group.gridx_entry,
  530. "global_gridy": self.general_options_form.general_gui_group.gridy_entry,
  531. "gerber_plot": self.gerber_options_form.gerber_gen_group.plot_cb,
  532. "gerber_solid": self.gerber_options_form.gerber_gen_group.solid_cb,
  533. "gerber_multicolored": self.gerber_options_form.gerber_gen_group.multicolored_cb,
  534. "gerber_isotooldia": self.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  535. "gerber_isopasses": self.gerber_options_form.gerber_opt_group.iso_width_entry,
  536. "gerber_isooverlap": self.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  537. "gerber_combine_passes": self.gerber_options_form.gerber_opt_group.combine_passes_cb,
  538. "gerber_noncoppermargin": self.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  539. "gerber_noncopperrounded": self.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  540. "gerber_bboxmargin": self.gerber_options_form.gerber_opt_group.bbmargin_entry,
  541. "gerber_bboxrounded": self.gerber_options_form.gerber_opt_group.bbrounded_cb,
  542. "excellon_plot": self.excellon_options_form.excellon_gen_group.plot_cb,
  543. "excellon_solid": self.excellon_options_form.excellon_gen_group.solid_cb,
  544. "excellon_format_upper_in": self.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  545. "excellon_format_lower_in": self.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  546. "excellon_format_upper_mm": self.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  547. "excellon_format_lower_mm": self.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  548. "excellon_zeros": self.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  549. "excellon_units": self.excellon_options_form.excellon_gen_group.excellon_units_radio,
  550. "excellon_optimization_type": self.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  551. "excellon_drillz": self.excellon_options_form.excellon_opt_group.cutz_entry,
  552. "excellon_travelz": self.excellon_options_form.excellon_opt_group.travelz_entry,
  553. "excellon_feedrate": self.excellon_options_form.excellon_opt_group.feedrate_entry,
  554. "excellon_feedrate_rapid": self.excellon_options_form.excellon_opt_group.feedrate_rapid_entry,
  555. "excellon_spindlespeed": self.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  556. "excellon_dwell": self.excellon_options_form.excellon_opt_group.dwell_cb,
  557. "excellon_dwelltime": self.excellon_options_form.excellon_opt_group.dwelltime_entry,
  558. "excellon_toolchange": self.excellon_options_form.excellon_opt_group.toolchange_cb,
  559. "excellon_toolchangez": self.excellon_options_form.excellon_opt_group.toolchangez_entry,
  560. "excellon_toolchangexy": self.excellon_options_form.excellon_opt_group.toolchangexy_entry,
  561. "excellon_tooldia": self.excellon_options_form.excellon_opt_group.tooldia_entry,
  562. "excellon_ppname_e": self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  563. "excellon_startz": self.excellon_options_form.excellon_opt_group.estartz_entry,
  564. "excellon_endz": self.excellon_options_form.excellon_opt_group.eendz_entry,
  565. "geometry_plot": self.geometry_options_form.geometry_gen_group.plot_cb,
  566. "geometry_cnctooldia": self.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  567. "geometry_segx": self.geometry_options_form.geometry_opt_group.segx_entry,
  568. "geometry_segy": self.geometry_options_form.geometry_opt_group.segy_entry,
  569. "geometry_cutz": self.geometry_options_form.geometry_opt_group.cutz_entry,
  570. "geometry_travelz": self.geometry_options_form.geometry_opt_group.travelz_entry,
  571. "geometry_feedrate": self.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  572. "geometry_feedrate_z": self.geometry_options_form.geometry_opt_group.cncplunge_entry,
  573. "geometry_feedrate_rapid": self.geometry_options_form.geometry_opt_group.cncfeedrate_rapid_entry,
  574. "geometry_spindlespeed": self.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  575. "geometry_dwell": self.geometry_options_form.geometry_opt_group.dwell_cb,
  576. "geometry_dwelltime": self.geometry_options_form.geometry_opt_group.dwelltime_entry,
  577. "geometry_ppname_g": self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  578. "geometry_toolchange": self.geometry_options_form.geometry_opt_group.toolchange_cb,
  579. "geometry_toolchangez": self.geometry_options_form.geometry_opt_group.toolchangez_entry,
  580. "geometry_toolchangexy": self.geometry_options_form.geometry_opt_group.toolchangexy_entry,
  581. "geometry_startz": self.geometry_options_form.geometry_opt_group.gstartz_entry,
  582. "geometry_endz": self.geometry_options_form.geometry_opt_group.gendz_entry,
  583. "geometry_depthperpass": self.geometry_options_form.geometry_opt_group.depthperpass_entry,
  584. "geometry_multidepth": self.geometry_options_form.geometry_opt_group.multidepth_cb,
  585. "geometry_extracut": self.geometry_options_form.geometry_opt_group.extracut_cb,
  586. "cncjob_plot": self.cncjob_options_form.cncjob_gen_group.plot_cb,
  587. "cncjob_tooldia": self.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  588. "cncjob_prepend": self.cncjob_options_form.cncjob_opt_group.prepend_text,
  589. "cncjob_append": self.cncjob_options_form.cncjob_opt_group.append_text,
  590. "tools_ncctools": self.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  591. "tools_nccoverlap": self.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  592. "tools_nccmargin": self.tools_options_form.tools_ncc_group.ncc_margin_entry,
  593. "tools_cutouttooldia": self.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  594. "tools_cutoutmargin": self.tools_options_form.tools_cutout_group.cutout_margin_entry,
  595. "tools_cutoutgapsize": self.tools_options_form.tools_cutout_group.cutout_gap_entry,
  596. "tools_gaps_rect": self.tools_options_form.tools_cutout_group.gaps_radio,
  597. "tools_gaps_ff": self.tools_options_form.tools_cutout_group.gaps_combo,
  598. "tools_painttooldia": self.tools_options_form.tools_paint_group.painttooldia_entry,
  599. "tools_paintoverlap": self.tools_options_form.tools_paint_group.paintoverlap_entry,
  600. "tools_paintmargin": self.tools_options_form.tools_paint_group.paintmargin_entry,
  601. "tools_paintmethod": self.tools_options_form.tools_paint_group.paintmethod_combo,
  602. "tools_selectmethod": self.tools_options_form.tools_paint_group.selectmethod_combo,
  603. "tools_pathconnect": self.tools_options_form.tools_paint_group.pathconnect_cb,
  604. "tools_paintcontour": self.tools_options_form.tools_paint_group.contour_cb,
  605. "tools_2sided_mirror_axis": self.tools_options_form.tools_2sided_group.mirror_axis_radio,
  606. "tools_2sided_axis_loc": self.tools_options_form.tools_2sided_group.axis_location_radio,
  607. "tools_2sided_drilldia": self.tools_options_form.tools_2sided_group.drill_dia_entry
  608. }
  609. for name in list(self.postprocessors.keys()):
  610. self.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  611. self.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  612. self.options = LoudDict()
  613. self.options.set_change_callback(self.on_options_dict_change)
  614. self.options.update({
  615. "units": "IN",
  616. "global_gridx": 1.0,
  617. "global_gridy": 1.0,
  618. "global_background_timeout": 300000, # Default value is 5 minutes
  619. "global_verbose_error_level": 0, # Shell verbosity:
  620. # 0 = default(python trace only for unknown errors),
  621. # 1 = show trace(show trace allways), 2 = (For the future).
  622. "gerber_plot": True,
  623. "gerber_solid": True,
  624. "gerber_multicolored": False,
  625. "gerber_isotooldia": 0.016,
  626. "gerber_isopasses": 1,
  627. "gerber_isooverlap": 0.15,
  628. "gerber_combine_passes": True,
  629. "gerber_noncoppermargin": 0.0,
  630. "gerber_noncopperrounded": False,
  631. "gerber_bboxmargin": 0.0,
  632. "gerber_bboxrounded": False,
  633. "excellon_plot": True,
  634. "excellon_solid": False,
  635. "excellon_format_upper_in": 2,
  636. "excellon_format_lower_in": 4,
  637. "excellon_format_upper_mm": 3,
  638. "excellon_format_lower_mm": 3,
  639. "excellon_units": 'INCH',
  640. "excellon_optimization_type": 'B',
  641. "excellon_search_time": 3,
  642. "excellon_zeros": "L",
  643. "excellon_drillz": -0.1,
  644. "excellon_travelz": 0.1,
  645. "excellon_feedrate": 3.0,
  646. "excellon_feedrate_rapid": 3.0,
  647. "excellon_spindlespeed": None,
  648. "excellon_dwell": True,
  649. "excellon_dwelltime": 1000,
  650. "excellon_toolchange": False,
  651. "excellon_toolchangez": 1.0,
  652. "excellon_toolchangexy": "0.0, 0.0",
  653. "excellon_tooldia": 0.016,
  654. "excellon_ppname_e": 'default',
  655. "excellon_startz": None,
  656. "excellon_endz": 2.0,
  657. "geometry_plot": True,
  658. "geometry_segx": 0.0,
  659. "geometry_segy": 0.0,
  660. "geometry_cutz": -0.002,
  661. "geometry_travelz": 0.1,
  662. "geometry_feedrate": 3.0,
  663. "geometry_feedrate_z": 3.0,
  664. "geometry_feedrate_rapid": 3.0,
  665. "geometry_spindlespeed": None,
  666. "geometry_dwell": True,
  667. "geometry_dwelltime": 1000,
  668. "geometry_cnctooldia": 0.016,
  669. "geometry_toolchange": False,
  670. "geometry_toolchangez": 2.0,
  671. "geometry_toolchangexy": "0.0, 0.0",
  672. "geometry_startz": None,
  673. "geometry_endz": 2.0,
  674. "geometry_ppname_g": "default",
  675. "geometry_depthperpass": 0.002,
  676. "geometry_multidepth": False,
  677. "geometry_extracut": False,
  678. "cncjob_plot": True,
  679. "cncjob_tooldia": 0.016,
  680. "cncjob_prepend": "",
  681. "cncjob_append": "",
  682. "tools_ncctools": "1.0, 0.5",
  683. "tools_nccoverlap": 0.4,
  684. "tools_nccmargin": 1,
  685. "tools_cutouttooldia": 0.07,
  686. "tools_cutoutmargin": 0.1,
  687. "tools_cutoutgapsize": 0.15,
  688. "tools_gaps_rect": "4",
  689. "tools_gaps_ff": "8",
  690. "tools_painttooldia": 0.07,
  691. "tools_paintoverlap": 0.15,
  692. "tools_paintmargin": 0.0,
  693. "tools_paintmethod": "seed",
  694. "tools_selectmethod": "single",
  695. "tools_pathconnect": True,
  696. "tools_paintcontour": True,
  697. "tools_2sided_mirror_axis": "X",
  698. "tools_2sided_axis_loc": 'point',
  699. "tools_2sided_drilldia": 1
  700. })
  701. self.options.update(self.defaults) # Copy app defaults to project options
  702. self.gen_form = None
  703. self.ger_form = None
  704. self.exc_form = None
  705. self.geo_form = None
  706. self.cnc_form = None
  707. self.tools_form = None
  708. self.on_options_combo_change(0) # Will show the initial form
  709. ### Define OBJECT COLLECTION ###
  710. self.collection = ObjectCollection(self)
  711. self.ui.project_tab_layout.addWidget(self.collection.view)
  712. ###
  713. self.log.debug("Finished creating Object Collection.")
  714. ### Initialize the color box's color in Preferences -> Global -> Color
  715. # Init Plot Colors
  716. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  717. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  718. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  719. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  720. int(self.defaults['global_plot_fill'][7:9], 16))
  721. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  722. int(self.defaults['global_plot_fill'][7:9], 16))
  723. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  724. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  725. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  726. # Init Left-Right Selection colors
  727. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  728. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  729. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  730. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  731. int(self.defaults['global_sel_fill'][7:9], 16))
  732. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  733. int(self.defaults['global_sel_fill'][7:9], 16))
  734. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  735. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  736. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  737. # Init Right-Left Selection colors
  738. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  739. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  740. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  741. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  742. int(self.defaults['global_sel_fill'][7:9], 16))
  743. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  744. int(self.defaults['global_sel_fill'][7:9], 16))
  745. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  746. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  747. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  748. # Init Draw color and Selection Draw Color
  749. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  750. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  751. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  752. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  753. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  754. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  755. #### End of Data ####
  756. #### Plot Area ####
  757. start_plot_time = time.time() # debug
  758. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  759. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  760. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  761. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  762. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  763. # Keys over plot enabled
  764. self.plotcanvas.vis_connect('key_press', self.on_key_over_plot)
  765. self.plotcanvas.vis_connect('key_release', self.on_key_release_over_plot)
  766. self.ui.splitter.setStretchFactor(1, 2)
  767. # So it can receive key presses
  768. self.plotcanvas.vispy_canvas.native.setFocus()
  769. self.app_cursor = self.plotcanvas.new_cursor()
  770. self.app_cursor.enabled = False
  771. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  772. # depending on from where those tools are called different actions can be done
  773. self.call_source = 'app'
  774. end_plot_time = time.time()
  775. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  776. ### EDITOR section
  777. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  778. self.exc_editor = FlatCAMExcEditor(self)
  779. # start with GRID activated
  780. self.ui.grid_snap_btn.trigger()
  781. self.ui.corner_snap_btn.setEnabled(False)
  782. self.ui.snap_max_dist_entry.setEnabled(False)
  783. self.ui.g_editor_cmenu.setEnabled(False)
  784. self.ui.e_editor_cmenu.setEnabled(False)
  785. #### Adjust tabs width ####
  786. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  787. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  788. self.collection.view.setMinimumWidth(290)
  789. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  790. #### Worker ####
  791. self.workers = WorkerStack()
  792. self.worker_task.connect(self.workers.add_task)
  793. ### Signal handling ###
  794. ## Custom signals
  795. self.inform.connect(self.info)
  796. self.message.connect(self.message_dialog)
  797. self.progress.connect(self.set_progress_bar)
  798. self.object_created.connect(self.on_object_created)
  799. self.object_changed.connect(self.on_object_changed)
  800. self.object_plotted.connect(self.on_object_plotted)
  801. self.plots_updated.connect(self.on_plots_updated)
  802. self.file_opened.connect(self.register_recent)
  803. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  804. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  805. ## Standard signals
  806. # Menu
  807. self.ui.menufilenew.triggered.connect(self.on_file_new_click)
  808. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  809. self.ui.menufileopengerber_follow.triggered.connect(self.on_fileopengerber_follow)
  810. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  811. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  812. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  813. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  814. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  815. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  816. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  817. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  818. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  819. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  820. self.ui.menufileexportexcellon.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=None))
  821. self.ui.menufileexportexcellon_altium.triggered.connect(lambda: self.on_file_exportexcellon(altium_format=True))
  822. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  823. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  824. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  825. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  826. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  827. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  828. self.ui.menueditnew.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  829. self.ui.menueditnewexc.triggered.connect(self.new_excellon_object)
  830. self.ui.menueditedit.triggered.connect(self.object2editor)
  831. self.ui.menueditok.triggered.connect(self.editor2object)
  832. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  833. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  834. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  835. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  836. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  837. self.ui.menueditdelete.triggered.connect(self.on_delete)
  838. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  839. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  840. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  841. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  842. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  843. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  844. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  845. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  846. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  847. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  848. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  849. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  850. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  851. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  852. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  853. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  854. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  855. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  856. self.ui.menuviewdisableall.triggered.connect(lambda: self.disable_plots(self.collection.get_list()))
  857. self.ui.menuviewdisableother.triggered.connect(lambda: self.disable_plots(self.collection.get_non_selected()))
  858. self.ui.menuviewenable.triggered.connect(lambda: self.enable_plots(self.collection.get_list()))
  859. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  860. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  861. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  862. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  863. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  864. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  865. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  866. self.ui.menuhelp_about.triggered.connect(self.on_about)
  867. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  868. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  869. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  870. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  871. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  872. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  873. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  874. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  875. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  876. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  877. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  878. # Toolbar
  879. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  880. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  881. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  882. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  883. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  884. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  885. self.ui.replot_btn.triggered.connect(self.plot_all)
  886. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  887. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  888. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  889. self.ui.newgeo_btn.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  890. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  891. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  892. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  893. self.ui.delete_btn.triggered.connect(self.on_delete)
  894. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  895. # Context Menu
  896. self.ui.popmenu_new_geo.triggered.connect(lambda: self.new_object('geometry', 'new_g', lambda x, y: None))
  897. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  898. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  899. self.ui.gridmenu_1.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.05"))
  900. self.ui.gridmenu_2.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.1"))
  901. self.ui.gridmenu_3.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.2"))
  902. self.ui.gridmenu_4.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("0.5"))
  903. self.ui.gridmenu_5.triggered.connect(lambda: self.ui.grid_gap_x_entry.setText("1.0"))
  904. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  905. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  906. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  907. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  908. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  909. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  910. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  911. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  912. self.ui.clearplot.triggered.connect(self.clear_plots)
  913. self.ui.replot.triggered.connect(self.plot_all)
  914. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  915. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  916. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  917. self.ui.popmenu_save.triggered.connect(self.editor2object)
  918. self.ui.popmenu_move.triggered.connect(self.obj_move)
  919. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  920. # Preferences Plot Area TAB
  921. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  922. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  923. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  924. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  925. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  926. ###############################
  927. ### GUI PREFERENCES SIGNALS ###
  928. ###############################
  929. self.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  930. self.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  931. ###############################
  932. ### GUI PREFERENCES SIGNALS ###
  933. ###############################
  934. # Setting plot colors signals
  935. self.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  936. self.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  937. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  938. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  939. self.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  940. self.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  941. # Setting selection (left - right) colors signals
  942. self.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  943. self.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  944. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  945. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  946. self.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  947. self.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  948. # Setting selection (right - left) colors signals
  949. self.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  950. self.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  951. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  952. self.on_alt_sf_color_spinner)
  953. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  954. self.on_alt_sf_color_slider)
  955. self.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  956. self.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  957. # Setting Editor Draw colors signals
  958. self.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  959. self.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  960. self.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  961. self.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  962. self.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  963. self.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  964. # Modify G-CODE Plot Area TAB
  965. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  966. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  967. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  968. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  969. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  970. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  971. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  972. # Object list
  973. self.collection.view.activated.connect(self.on_row_activated)
  974. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  975. self.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  976. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  977. self.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  978. self.on_excellon_defaults_button)
  979. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  980. self.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  981. self.on_excellon_options_button)
  982. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  983. self.tool_tab_locked = False
  984. ####################
  985. ### Other setups ###
  986. ####################
  987. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  988. self.setup_obj_classes()
  989. self.setup_recent_items()
  990. self.setup_component_editor()
  991. #############
  992. ### Shell ###
  993. #############
  994. ###
  995. # Auto-complete KEYWORDS
  996. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  997. 'aligndrill', 'clear',
  998. 'aligndrillgrid', 'cncjob', 'cutout', 'cutout_any', 'delete', 'drillcncjob',
  999. 'export_gcode',
  1000. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1001. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1002. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1003. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1004. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1005. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1006. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1007. ]
  1008. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1009. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1010. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1011. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1012. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1013. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1014. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1015. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1016. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1017. ]
  1018. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1019. self.shell = FCShell(self, version=self.version)
  1020. self.shell._edit.set_model_data(self.myKeywords)
  1021. self.shell.setWindowIcon(self.ui.app_icon)
  1022. self.shell.setWindowTitle("FlatCAM Shell")
  1023. self.shell.resize(*self.defaults["global_shell_shape"])
  1024. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1025. self.shell.append_output("(Type help to get started)\n\n")
  1026. self.init_tcl()
  1027. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1028. self.ui.shell_dock.setWidget(self.shell)
  1029. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1030. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1031. QtWidgets.QDockWidget.DockWidgetFloatable |
  1032. QtWidgets.QDockWidget.DockWidgetClosable)
  1033. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1034. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1035. if self.defaults["global_shell_at_startup"]:
  1036. self.ui.shell_dock.show()
  1037. else:
  1038. self.ui.shell_dock.hide()
  1039. #########################
  1040. ### Tools and Plugins ###
  1041. #########################
  1042. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1043. self.install_tools()
  1044. ### System Font Parsing ###
  1045. # self.f_parse = ParseFont(self)
  1046. # self.parse_system_fonts()
  1047. # test if the program was started with a script as parameter
  1048. if self.cmd_line_shellfile:
  1049. try:
  1050. with open(self.cmd_line_shellfile, "r") as myfile:
  1051. cmd_line_shellfile_text = myfile.read()
  1052. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1053. except Exception as ext:
  1054. print("ERROR: ", ext)
  1055. sys.exit(2)
  1056. ###########################
  1057. #### Check for updates ####
  1058. ###########################
  1059. # Separate thread (Not worker)
  1060. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1061. if (self.beta is False or self.beta is None) and \
  1062. self.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1063. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1064. self.thr2 = QtCore.QThread()
  1065. self.worker_task.emit({'fcn': self.version_check,
  1066. 'params': []})
  1067. self.thr2.start()
  1068. ####################################
  1069. #### Variables for global usage ####
  1070. ####################################
  1071. # coordinates for relative position display
  1072. self.rel_point1 = (0, 0)
  1073. self.rel_point2 = (0, 0)
  1074. # variable to store coordinates
  1075. self.pos = (0, 0)
  1076. self.pos_jump = (0, 0)
  1077. # variable to store if there was motion before right mouse button click (panning)
  1078. self.panning_action = False
  1079. # variable to store if a command is active (then the var is not None) and which one it is
  1080. self.command_active = None
  1081. # variable to store the status of moving selection action
  1082. # None value means that it's not an selection action
  1083. # True value = a selection from left to right
  1084. # False value = a selection from right to left
  1085. self.selection_type = None
  1086. # List to store the objects that are currently loaded in FlatCAM
  1087. # This list is updated on each object creation or object delete
  1088. self.all_objects_list = []
  1089. # List to store the objects that are selected
  1090. self.sel_objects_list = []
  1091. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1092. self.key_modifiers = None
  1093. # Variable to hold the status of the axis
  1094. self.toggle_axis = True
  1095. self.cursor = None
  1096. # Variable to store the GCODE that was edited
  1097. self.gcode_edited = ""
  1098. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1099. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1100. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1101. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1102. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1103. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1104. 'mpf']
  1105. self.svg_list = ['svg']
  1106. self.dxf_list = ['dxf']
  1107. self.prj_list = ['flatprj']
  1108. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1109. # flag for polygons not cleared
  1110. self.poly_not_cleared = False
  1111. ### Save defaults to factory_defaults.FlatConfig file ###
  1112. ### It's done only once after install #############
  1113. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1114. fac_def_from_file = factory_file.read()
  1115. factory_defaults = json.loads(fac_def_from_file)
  1116. # if the file contain an empty dictionary then save the factory defaults into the file
  1117. if not factory_defaults:
  1118. self.save_factory_defaults(silent=False)
  1119. factory_file.close()
  1120. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1121. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1122. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1123. # Post-GUI initialization: Experimental attempt
  1124. # to perform unit tests on the GUI.
  1125. # if post_gui is not None:
  1126. # post_gui(self)
  1127. App.log.debug("END of constructor. Releasing control.")
  1128. # accept a project file as command line parameter
  1129. # the path/file_name must be enclosed in quotes if it contain spaces
  1130. for argument in App.args:
  1131. if '.FlatPrj' in argument:
  1132. try:
  1133. project_name = str(argument)
  1134. if project_name == "":
  1135. self.inform.emit("Open cancelled.")
  1136. else:
  1137. # self.open_project(project_name)
  1138. run_from_arg = True
  1139. self.worker_task.emit({'fcn': self.open_project,
  1140. 'params': [project_name, run_from_arg]})
  1141. except Exception as e:
  1142. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1143. def defaults_read_form(self):
  1144. for option in self.defaults_form_fields:
  1145. try:
  1146. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1147. except:
  1148. pass
  1149. def defaults_write_form(self):
  1150. for option in self.defaults:
  1151. self.defaults_write_form_field(option)
  1152. # try:
  1153. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1154. # except KeyError:
  1155. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1156. # # TODO: Rethink this?
  1157. # pass
  1158. def defaults_write_form_field(self, field):
  1159. try:
  1160. self.defaults_form_fields[field].set_value(self.defaults[field])
  1161. except KeyError:
  1162. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1163. # TODO: Rethink this?
  1164. pass
  1165. def clear_pool(self):
  1166. self.pool.close()
  1167. self.pool = Pool()
  1168. self.pool_recreated.emit(self.pool)
  1169. gc.collect()
  1170. # the order that the tools are installed is important as they can depend on each other install position
  1171. def install_tools(self):
  1172. self.dblsidedtool = DblSidedTool(self)
  1173. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1174. self.measurement_tool = Measurement(self)
  1175. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1176. self.panelize_tool = Panelize(self)
  1177. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1178. self.film_tool = Film(self)
  1179. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'), separator=True)
  1180. self.move_tool = ToolMove(self)
  1181. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1182. before=self.ui.menueditorigin)
  1183. self.cutout_tool = ToolCutout(self)
  1184. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1185. before=self.measurement_tool.menuAction)
  1186. self.ncclear_tool = NonCopperClear(self)
  1187. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1188. before=self.measurement_tool.menuAction, separator=True)
  1189. self.paint_tool = ToolPaint(self)
  1190. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1191. before=self.measurement_tool.menuAction, separator=True)
  1192. self.calculator_tool = ToolCalculator(self)
  1193. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1194. self.transform_tool = ToolTransform(self)
  1195. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1196. self.properties_tool = Properties(self)
  1197. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1198. self.image_tool = ToolImage(self)
  1199. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1200. separator=True)
  1201. self.log.debug("Tools are installed.")
  1202. def init_tools(self):
  1203. # delete the data currently in the Tools Tab and the Tab itself
  1204. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1205. if widget is not None:
  1206. widget.deleteLater()
  1207. self.ui.notebook.removeTab(2)
  1208. # rebuild the Tools Tab
  1209. self.ui.tool_tab = QtWidgets.QWidget()
  1210. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1211. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1212. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1213. self.ui.tool_scroll_area = VerticalScrollArea()
  1214. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1215. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1216. self.install_tools()
  1217. self.log.debug("Tools are initialized.")
  1218. # def parse_system_fonts(self):
  1219. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1220. # 'params': []})
  1221. def object2editor(self):
  1222. """
  1223. Send the current Geometry or Excellon object (if any) into the editor.
  1224. :return: None
  1225. """
  1226. # adjust the visibility of some of the canvas context menu
  1227. self.ui.popmenu_edit.setVisible(False)
  1228. self.ui.popmenu_save.setVisible(True)
  1229. if isinstance(self.collection.get_active(), FlatCAMGeometry):
  1230. edited_object = self.collection.get_active()
  1231. # for now, if the Geometry is MultiGeo do not allow the editing
  1232. if edited_object.multigeo is True:
  1233. self.inform.emit("[warning_notcl]Editing a MultiGeo Geometry is not possible for the moment.")
  1234. return
  1235. self.ui.update_obj_btn.setEnabled(True)
  1236. self.geo_editor.edit_fcgeometry(edited_object)
  1237. self.ui.g_editor_cmenu.setEnabled(True)
  1238. # set call source to the Editor we go into
  1239. self.call_source = 'geo_editor'
  1240. # prevent the user to change anything in the Selected Tab while the Geo Editor is active
  1241. sel_tab_widget_list = self.ui.selected_tab.findChildren(QtWidgets.QWidget)
  1242. for w in sel_tab_widget_list:
  1243. w.setEnabled(False)
  1244. elif isinstance(self.collection.get_active(), FlatCAMExcellon):
  1245. self.ui.update_obj_btn.setEnabled(True)
  1246. self.exc_editor.edit_exc_obj(self.collection.get_active())
  1247. self.ui.e_editor_cmenu.setEnabled(True)
  1248. # set call source to the Editor we go into
  1249. self.call_source = 'exc_editor'
  1250. else:
  1251. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to edit.")
  1252. return
  1253. # make sure that we can't select another object while in Editor Mode:
  1254. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1255. # delete any selection shape that might be active as they are not relevant in Editor
  1256. self.delete_selection_shape()
  1257. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1258. self.inform.emit("[warning_notcl]Editor is activated ...")
  1259. def editor2object(self):
  1260. """
  1261. Transfers the Geometry or Excellon from the editor to the current object.
  1262. :return: None
  1263. """
  1264. # adjust the visibility of some of the canvas context menu
  1265. self.ui.popmenu_edit.setVisible(True)
  1266. self.ui.popmenu_save.setVisible(False)
  1267. edited_obj = self.collection.get_active()
  1268. obj_type = ""
  1269. if isinstance(edited_obj, FlatCAMGeometry):
  1270. obj_type = "Geometry"
  1271. self.geo_editor.update_fcgeometry(edited_obj)
  1272. self.geo_editor.update_options(edited_obj)
  1273. self.geo_editor.deactivate()
  1274. # edited_obj.on_tool_delete(all=True)
  1275. # edited_obj.on_tool_add(dia=edited_obj.options['cnctooldia'])
  1276. self.ui.corner_snap_btn.setEnabled(False)
  1277. self.ui.update_obj_btn.setEnabled(False)
  1278. self.ui.g_editor_cmenu.setEnabled(False)
  1279. self.ui.e_editor_cmenu.setEnabled(False)
  1280. # update the geo object options so it is including the bounding box values
  1281. try:
  1282. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1283. edited_obj.options['xmin'] = xmin
  1284. edited_obj.options['ymin'] = ymin
  1285. edited_obj.options['xmax'] = xmax
  1286. edited_obj.options['ymax'] = ymax
  1287. except AttributeError:
  1288. self.inform.emit("[warning] Object empty after edit.")
  1289. elif isinstance(edited_obj, FlatCAMExcellon):
  1290. obj_type = "Excellon"
  1291. self.exc_editor.update_exc_obj(edited_obj)
  1292. self.exc_editor.deactivate()
  1293. self.ui.corner_snap_btn.setEnabled(False)
  1294. self.ui.update_obj_btn.setEnabled(False)
  1295. self.ui.g_editor_cmenu.setEnabled(False)
  1296. self.ui.e_editor_cmenu.setEnabled(False)
  1297. else:
  1298. self.inform.emit("[warning_notcl]Select a Geometry or Excellon Object to update.")
  1299. return
  1300. # restore the call_source to app
  1301. self.call_source = 'app'
  1302. edited_obj.plot()
  1303. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1304. self.inform.emit("[success] %s is updated, returning to App..." % obj_type)
  1305. # reset the Object UI to original settings
  1306. # edited_obj.set_ui(edited_obj.ui_type())
  1307. # edited_obj.build_ui()
  1308. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1309. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1310. def get_last_folder(self):
  1311. return self.defaults["global_last_folder"]
  1312. def get_last_save_folder(self):
  1313. return self.defaults["global_last_save_folder"]
  1314. def report_usage(self, resource):
  1315. """
  1316. Increments usage counter for the given resource
  1317. in self.defaults['global_stats'].
  1318. :param resource: Name of the resource.
  1319. :return: None
  1320. """
  1321. if resource in self.defaults['global_stats']:
  1322. self.defaults['global_stats'][resource] += 1
  1323. else:
  1324. self.defaults['global_stats'][resource] = 1
  1325. def init_tcl(self):
  1326. if hasattr(self,'tcl'):
  1327. # self.tcl = None
  1328. # TODO we need to clean non default variables and procedures here
  1329. # new object cannot be used here as it will not remember values created for next passes,
  1330. # because tcl was execudted in old instance of TCL
  1331. pass
  1332. else:
  1333. self.tcl = tk.Tcl()
  1334. self.setup_shell()
  1335. self.log.debug("TCL Shell has been initialized.")
  1336. # TODO: This shouldn't be here.
  1337. class TclErrorException(Exception):
  1338. """
  1339. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1340. """
  1341. pass
  1342. def shell_message(self, msg, show=False, error=False):
  1343. """
  1344. Shows a message on the FlatCAM Shell
  1345. :param msg: Message to display.
  1346. :param show: Opens the shell.
  1347. :param error: Shows the message as an error.
  1348. :return: None
  1349. """
  1350. if show:
  1351. self.ui.shell_dock.show()
  1352. try:
  1353. if error:
  1354. self.shell.append_error(msg + "\n")
  1355. else:
  1356. self.shell.append_output(msg + "\n")
  1357. except AttributeError:
  1358. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1359. def raise_tcl_unknown_error(self, unknownException):
  1360. """
  1361. Raise exception if is different type than TclErrorException
  1362. this is here mainly to show unknown errors inside TCL shell console.
  1363. :param unknownException:
  1364. :return:
  1365. """
  1366. if not isinstance(unknownException, self.TclErrorException):
  1367. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1368. else:
  1369. raise unknownException
  1370. def display_tcl_error(self, error, error_info=None):
  1371. """
  1372. escape bracket [ with \ otherwise there is error
  1373. "ERROR: missing close-bracket" instead of real error
  1374. :param error: it may be text or exception
  1375. :return: None
  1376. """
  1377. if isinstance(error, Exception):
  1378. exc_type, exc_value, exc_traceback = error_info
  1379. if not isinstance(error, self.TclErrorException):
  1380. show_trace = 1
  1381. else:
  1382. show_trace = int(self.defaults['global_verbose_error_level'])
  1383. if show_trace > 0:
  1384. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1385. trc_formated = []
  1386. for a in reversed(trc):
  1387. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1388. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1389. exc_type,
  1390. "\n".join(trc_formated))
  1391. else:
  1392. text = "%s" % error
  1393. else:
  1394. text = error
  1395. text = text.replace('[', '\\[').replace('"', '\\"')
  1396. self.tcl.eval('return -code error "%s"' % text)
  1397. def raise_tcl_error(self, text):
  1398. """
  1399. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1400. :param text: text of error
  1401. :return: raise exception
  1402. """
  1403. self.display_tcl_error(text)
  1404. raise self.TclErrorException(text)
  1405. def exec_command(self, text):
  1406. """
  1407. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1408. Also handles execution in separated threads
  1409. :param text:
  1410. :return: output if there was any
  1411. """
  1412. self.report_usage('exec_command')
  1413. result = self.exec_command_test(text, False)
  1414. #MS: added this method call so the geometry is updated once the TCL
  1415. #command is executed
  1416. self.plot_all()
  1417. return result
  1418. def exec_command_test(self, text, reraise=True):
  1419. """
  1420. Same as exec_command(...) with additional control over exceptions.
  1421. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1422. :param text: Input command
  1423. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1424. :return: Output from the command
  1425. """
  1426. text = str(text)
  1427. try:
  1428. self.shell.open_proccessing() # Disables input box.
  1429. result = self.tcl.eval(str(text))
  1430. if result != 'None':
  1431. self.shell.append_output(result + '\n')
  1432. except tk.TclError as e:
  1433. # This will display more precise answer if something in TCL shell fails
  1434. result = self.tcl.eval("set errorInfo")
  1435. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1436. self.shell.append_error('ERROR: ' + result + '\n')
  1437. # Show error in console and just return or in test raise exception
  1438. if reraise:
  1439. raise e
  1440. finally:
  1441. self.shell.close_proccessing()
  1442. pass
  1443. return result
  1444. # """
  1445. # Code below is unsused. Saved for later.
  1446. # """
  1447. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1448. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1449. # self.log.debug(parts)
  1450. # try:
  1451. # if parts[0] not in commands:
  1452. # self.shell.append_error("Unknown command\n")
  1453. # return
  1454. #
  1455. # #import inspect
  1456. # #inspect.getargspec(someMethod)
  1457. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1458. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1459. # self.shell.append_error(
  1460. # "Command %s takes %d arguments. %d given.\n" %
  1461. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1462. # )
  1463. # return
  1464. #
  1465. # cmdfcn = commands[parts[0]]["fcn"]
  1466. # cmdconv = commands[parts[0]]["converters"]
  1467. # if len(parts) - 1 > 0:
  1468. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1469. # else:
  1470. # retval = cmdfcn()
  1471. # retfcn = commands[parts[0]]["retfcn"]
  1472. # if retval and retfcn(retval):
  1473. # self.shell.append_output(retfcn(retval) + "\n")
  1474. #
  1475. # except Exception as e:
  1476. # #self.shell.append_error(''.join(traceback.format_exc()))
  1477. # #self.shell.append_error("?\n")
  1478. # self.shell.append_error(str(e) + "\n")
  1479. def info(self, msg):
  1480. """
  1481. Informs the user. Normally on the status bar, optionally
  1482. also on the shell.
  1483. :param msg: Text to write.
  1484. :return: None
  1485. """
  1486. # Type of message in brackets at the begining of the message.
  1487. match = re.search("\[([^\]]+)\](.*)", msg)
  1488. if match:
  1489. level = match.group(1)
  1490. msg_ = match.group(2)
  1491. self.ui.fcinfo.set_status(str(msg_), level=level)
  1492. if level == "error" or level == "warning":
  1493. self.shell_message(msg, error=True, show=True)
  1494. elif level == "error_notcl" or level == "warning_notcl":
  1495. self.shell_message(msg, error=True, show=False)
  1496. else:
  1497. self.shell_message(msg, error=False, show=False)
  1498. else:
  1499. self.ui.fcinfo.set_status(str(msg), level="info")
  1500. # make sure that if the message is to clear the infobar with a space
  1501. # is not printed over and over on the shell
  1502. if msg != '':
  1503. self.shell_message(msg)
  1504. def restore_toolbar_view(self):
  1505. tb = self.defaults["global_toolbar_view"]
  1506. if tb & 1:
  1507. self.ui.toolbarfile.setVisible(True)
  1508. else:
  1509. self.ui.toolbarfile.setVisible(False)
  1510. if tb & 2:
  1511. self.ui.toolbargeo.setVisible(True)
  1512. else:
  1513. self.ui.toolbargeo.setVisible(False)
  1514. if tb & 4:
  1515. self.ui.toolbarview.setVisible(True)
  1516. else:
  1517. self.ui.toolbarview.setVisible(False)
  1518. if tb & 8:
  1519. self.ui.toolbartools.setVisible(True)
  1520. else:
  1521. self.ui.toolbartools.setVisible(False)
  1522. if tb & 16:
  1523. self.ui.snap_toolbar.setVisible(True)
  1524. else:
  1525. self.ui.snap_toolbar.setVisible(False)
  1526. def load_defaults(self, filename):
  1527. """
  1528. Loads the aplication's default settings from current_defaults.FlatConfig into
  1529. ``self.defaults``.
  1530. :return: None
  1531. """
  1532. try:
  1533. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1534. options = f.read()
  1535. f.close()
  1536. except IOError:
  1537. self.log.error("Could not load defaults file.")
  1538. self.inform.emit("[error] Could not load defaults file.")
  1539. # in case the defaults file can't be loaded, show all toolbars
  1540. self.defaults["global_toolbar_view"] = 31
  1541. return
  1542. try:
  1543. defaults = json.loads(options)
  1544. except:
  1545. # in case the defaults file can't be loaded, show all toolbars
  1546. self.defaults["global_toolbar_view"] = 31
  1547. e = sys.exc_info()[0]
  1548. App.log.error(str(e))
  1549. self.inform.emit("[error] Failed to parse defaults file.")
  1550. return
  1551. self.defaults.update(defaults)
  1552. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1553. # restore the toolbar view
  1554. self.restore_toolbar_view()
  1555. def on_import_preferences(self):
  1556. """
  1557. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1558. ``self.defaults``.
  1559. :return: None
  1560. """
  1561. self.report_usage("on_import_preferences")
  1562. App.log.debug("on_import_preferences()")
  1563. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1564. try:
  1565. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1566. directory=self.data_path, filter=filter)
  1567. except TypeError:
  1568. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1569. filename = str(filename)
  1570. if filename == "":
  1571. self.inform.emit("[warning_notcl]FlatCAM preferences import cancelled.")
  1572. else:
  1573. try:
  1574. f = open(filename)
  1575. options = f.read()
  1576. f.close()
  1577. except IOError:
  1578. self.log.error("Could not load defaults file.")
  1579. self.inform.emit("[error_notcl] Could not load defaults file.")
  1580. return
  1581. try:
  1582. defaults_from_file = json.loads(options)
  1583. except:
  1584. e = sys.exc_info()[0]
  1585. App.log.error(str(e))
  1586. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1587. return
  1588. self.defaults.update(defaults_from_file)
  1589. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1590. def on_export_preferences(self):
  1591. self.report_usage("on_export_preferences")
  1592. App.log.debug("on_export_preferences()")
  1593. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1594. try:
  1595. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences",
  1596. directory=self.data_path, filter=filter)
  1597. except TypeError:
  1598. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1599. filename = str(filename)
  1600. defaults_from_file = {}
  1601. if filename == "":
  1602. self.inform.emit("[warning_notcl]FlatCAM preferences export cancelled.")
  1603. return
  1604. else:
  1605. try:
  1606. f = open(filename, 'w')
  1607. defaults_file_content = f.read()
  1608. f.close()
  1609. except IOError:
  1610. App.log.debug('Creating a new preferences file ...')
  1611. f = open(filename, 'w')
  1612. json.dump({}, f)
  1613. f.close()
  1614. except:
  1615. e = sys.exc_info()[0]
  1616. App.log.error("Could not load defaults file.")
  1617. App.log.error(str(e))
  1618. self.inform.emit("[error_notcl]Could not load defaults file.")
  1619. return
  1620. try:
  1621. defaults_from_file = json.loads(defaults_file_content)
  1622. except:
  1623. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1624. # Update options
  1625. self.defaults_read_form()
  1626. defaults_from_file.update(self.defaults)
  1627. self.propagate_defaults(silent=True)
  1628. # Save update options
  1629. try:
  1630. f = open(filename, "w")
  1631. json.dump(defaults_from_file, f)
  1632. f.close()
  1633. except:
  1634. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1635. return
  1636. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1637. def on_preferences_open_folder(self):
  1638. if sys.platform == 'win32':
  1639. subprocess.Popen('explorer %s' % self.data_path)
  1640. elif sys.platform == 'darwin':
  1641. os.system('open "%s"' % self.data_path)
  1642. else:
  1643. subprocess.Popen(['xdg-open', self.data_path])
  1644. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1645. def save_geometry(self, x, y, width, height, notebook_width):
  1646. self.defaults["global_def_win_x"] = x
  1647. self.defaults["global_def_win_y"] = y
  1648. self.defaults["global_def_win_w"] = width
  1649. self.defaults["global_def_win_h"] = height
  1650. self.defaults["def_notebook_width"] = notebook_width
  1651. self.save_defaults()
  1652. def message_dialog(self, title, message, kind="info"):
  1653. icon = {"info": QtWidgets.QMessageBox.Information,
  1654. "warning": QtWidgets.QMessageBox.Warning,
  1655. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1656. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1657. dlg.setText(message)
  1658. dlg.exec_()
  1659. def register_recent(self, kind, filename):
  1660. self.log.debug("register_recent()")
  1661. self.log.debug(" %s" % kind)
  1662. self.log.debug(" %s" % filename)
  1663. record = {'kind': str(kind), 'filename': str(filename)}
  1664. if record in self.recent:
  1665. return
  1666. self.recent.insert(0, record)
  1667. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1668. self.recent.pop()
  1669. try:
  1670. f = open(self.data_path + '/recent.json', 'w')
  1671. except IOError:
  1672. App.log.error("Failed to open recent items file for writing.")
  1673. self.inform.emit('[error_notcl]Failed to open recent files file for writing.')
  1674. return
  1675. #try:
  1676. json.dump(self.recent, f)
  1677. # except:
  1678. # App.log.error("Failed to write to recent items file.")
  1679. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1680. # f.close()
  1681. f.close()
  1682. # Re-buid the recent items menu
  1683. self.setup_recent_items()
  1684. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1685. """
  1686. Creates a new specalized FlatCAMObj and attaches it to the application,
  1687. this is, updates the GUI accordingly, any other records and plots it.
  1688. This method is thread-safe.
  1689. Notes:
  1690. * If the name is in use, the self.collection will modify it
  1691. when appending it to the collection. There is no need to handle
  1692. name conflicts here.
  1693. :param kind: The kind of object to create. One of 'gerber',
  1694. 'excellon', 'cncjob' and 'geometry'.
  1695. :type kind: str
  1696. :param name: Name for the object.
  1697. :type name: str
  1698. :param initialize: Function to run after creation of the object
  1699. but before it is attached to the application. The function is
  1700. called with 2 parameters: the new object and the App instance.
  1701. :type initialize: function
  1702. :return: None
  1703. :rtype: None
  1704. """
  1705. App.log.debug("new_object()")
  1706. self.plot = plot
  1707. self.autoselected = autoselected
  1708. t0 = time.time() # Debug
  1709. ## Create object
  1710. classdict = {
  1711. "gerber": FlatCAMGerber,
  1712. "excellon": FlatCAMExcellon,
  1713. "cncjob": FlatCAMCNCjob,
  1714. "geometry": FlatCAMGeometry
  1715. }
  1716. App.log.debug("Calling object constructor...")
  1717. obj = classdict[kind](name)
  1718. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1719. # Set options from "Project options" form
  1720. self.options_read_form()
  1721. # IMPORTANT
  1722. # The key names in defaults and options dictionary's are not random:
  1723. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1724. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1725. # the options from project options form into the self.options. After that, below, depending on the type of
  1726. # object that is created, it will strip the name of the object and the underline (if the original key was
  1727. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1728. # "toolchange"
  1729. for option in self.options:
  1730. if option.find(kind + "_") == 0:
  1731. oname = option[len(kind) + 1:]
  1732. obj.options[oname] = self.options[option]
  1733. # if kind == 'geometry':
  1734. # obj.tools = {}
  1735. # elif kind == 'cncjob':
  1736. # obj.cnc_tools = {}
  1737. # Initialize as per user request
  1738. # User must take care to implement initialize
  1739. # in a thread-safe way as is is likely that we
  1740. # have been invoked in a separate thread.
  1741. t1 = time.time()
  1742. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  1743. try:
  1744. return_value = initialize(obj, self)
  1745. except Exception as e:
  1746. msg = "[error_notcl] An internal error has ocurred. See shell.\n"
  1747. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  1748. msg += traceback.format_exc()
  1749. self.inform.emit(msg)
  1750. # if str(e) == "Empty Geometry":
  1751. # self.inform.emit("[error_notcl] )
  1752. # else:
  1753. # self.inform.emit("[error] Object (%s) failed because: %s" % (kind, str(e)))
  1754. return "fail"
  1755. t2 = time.time()
  1756. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  1757. if return_value == 'fail':
  1758. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  1759. return "fail"
  1760. # Check units and convert if necessary
  1761. # This condition CAN be true because initialize() can change obj.units
  1762. if self.options["units"].upper() != obj.units.upper():
  1763. self.inform.emit("Converting units to " + self.options["units"] + ".")
  1764. obj.convert_units(self.options["units"])
  1765. t3 = time.time()
  1766. self.log.debug("%f seconds converting units." % (t3 - t2))
  1767. # Create the bounding box for the object and then add the results to the obj.options
  1768. try:
  1769. xmin, ymin, xmax, ymax = obj.bounds()
  1770. obj.options['xmin'] = xmin
  1771. obj.options['ymin'] = ymin
  1772. obj.options['xmax'] = xmax
  1773. obj.options['ymax'] = ymax
  1774. except:
  1775. log.warning("The object has no bounds properties.")
  1776. pass
  1777. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  1778. # Move the object to the main thread and let the app know that it is available.
  1779. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  1780. self.object_created.emit(obj, self.plot, self.autoselected)
  1781. return obj
  1782. def new_excellon_object(self):
  1783. self.new_object('excellon', 'new_e', lambda x, y: None)
  1784. def on_object_created(self, obj, plot, autoselect):
  1785. """
  1786. Event callback for object creation.
  1787. :param obj: The newly created FlatCAM object.
  1788. :return: None
  1789. """
  1790. t0 = time.time() # DEBUG
  1791. self.log.debug("on_object_created()")
  1792. # The Collection might change the name if there is a collision
  1793. self.collection.append(obj)
  1794. # after adding the object to the collection always update the list of objects that are in the collection
  1795. self.all_objects_list = self.collection.get_list()
  1796. self.inform.emit("[success]Object (%s) created: %s" % (obj.kind, obj.options['name']))
  1797. self.new_object_available.emit(obj)
  1798. # update the SHELL auto-completer model with the name of the new object
  1799. self.myKeywords.append(obj.options['name'])
  1800. self.shell._edit.set_model_data(self.myKeywords)
  1801. if autoselect:
  1802. # select the just opened object but deselect the previous ones
  1803. self.collection.set_all_inactive()
  1804. self.collection.set_active(obj.options["name"])
  1805. def worker_task(obj):
  1806. with self.proc_container.new("Plotting"):
  1807. obj.plot()
  1808. t1 = time.time() # DEBUG
  1809. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  1810. self.object_plotted.emit(obj)
  1811. # Send to worker
  1812. # self.worker.add_task(worker_task, [self])
  1813. if plot:
  1814. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  1815. def on_object_changed(self, obj):
  1816. # update the bounding box data from obj.options
  1817. xmin, ymin, xmax, ymax = obj.bounds()
  1818. obj.options['xmin'] = xmin
  1819. obj.options['ymin'] = ymin
  1820. obj.options['xmax'] = xmax
  1821. obj.options['ymax'] = ymax
  1822. log.debug("Object changed, updating the bounding box data on self.options")
  1823. # delete the old selection shape
  1824. self.delete_selection_shape()
  1825. def on_object_plotted(self, obj):
  1826. self.on_zoom_fit(None)
  1827. def options_read_form(self):
  1828. for option in self.options_form_fields:
  1829. self.options[option] = self.options_form_fields[option].get_value()
  1830. def options_write_form(self):
  1831. for option in self.options:
  1832. self.options_write_form_field(option)
  1833. def options_write_form_field(self, field):
  1834. try:
  1835. self.options_form_fields[field].set_value(self.options[field])
  1836. except KeyError:
  1837. # Changed from error to debug. This allows to have data stored
  1838. # which is not user-editable.
  1839. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  1840. pass
  1841. def on_about(self):
  1842. """
  1843. Displays the "about" dialog.
  1844. :return: None
  1845. """
  1846. self.report_usage("on_about")
  1847. version = self.version
  1848. version_date = self.version_date
  1849. beta = self.beta
  1850. class AboutDialog(QtWidgets.QDialog):
  1851. def __init__(self, parent=None):
  1852. QtWidgets.QDialog.__init__(self, parent)
  1853. # Icon and title
  1854. self.setWindowIcon(parent.app_icon)
  1855. self.setWindowTitle("FlatCAM")
  1856. layout1 = QtWidgets.QVBoxLayout()
  1857. self.setLayout(layout1)
  1858. layout2 = QtWidgets.QHBoxLayout()
  1859. layout1.addLayout(layout2)
  1860. logo = QtWidgets.QLabel()
  1861. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  1862. layout2.addWidget(logo, stretch=0)
  1863. title = QtWidgets.QLabel(
  1864. "<font size=8><B>FlatCAM</B></font><BR>"
  1865. "Version %s %s (%s) - %s <BR>"
  1866. "<BR>"
  1867. "2D Computer-Aided Printed Circuit Board<BR>"
  1868. "Manufacturing.<BR>"
  1869. "<BR>"
  1870. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  1871. "<BR>"
  1872. "<B> Main Contributors:</B><BR>"
  1873. "Denis Hayrullin<BR>"
  1874. "Kamil Sopko<BR>"
  1875. "Marius Stanciu<BR>"
  1876. "Matthieu Berthomé<BR>"
  1877. "and many others found "
  1878. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  1879. "<BR>"
  1880. "Development is done "
  1881. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  1882. "DOWNLOAD area "
  1883. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  1884. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  1885. )
  1886. title.setOpenExternalLinks(True)
  1887. layout2.addWidget(title, stretch=1)
  1888. layout3 = QtWidgets.QHBoxLayout()
  1889. layout1.addLayout(layout3)
  1890. layout3.addStretch()
  1891. okbtn = QtWidgets.QPushButton("Close")
  1892. layout3.addWidget(okbtn)
  1893. okbtn.clicked.connect(self.accept)
  1894. AboutDialog(self.ui).exec_()
  1895. def on_file_savedefaults(self):
  1896. """
  1897. Callback for menu item File->Save Defaults. Saves application default options
  1898. ``self.defaults`` to current_defaults.FlatConfig.
  1899. :return: None
  1900. """
  1901. self.save_defaults()
  1902. def on_app_exit(self):
  1903. if self.collection.get_list():
  1904. msgbox = QtWidgets.QMessageBox()
  1905. # msgbox.setText("<B>Save changes ...</B>")
  1906. msgbox.setText("There are files/objects opened in FlatCAM. "
  1907. "\n"
  1908. "Do you want to Save the project?")
  1909. msgbox.setWindowTitle("Save changes")
  1910. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  1911. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  1912. QtWidgets.QMessageBox.Cancel)
  1913. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  1914. response = msgbox.exec_()
  1915. if response == QtWidgets.QMessageBox.Yes:
  1916. self.on_file_saveprojectas(thread=False)
  1917. elif response == QtWidgets.QMessageBox.Cancel:
  1918. return
  1919. self.save_defaults()
  1920. else:
  1921. self.save_defaults()
  1922. log.debug("Application defaults saved ... Exit event.")
  1923. QtWidgets.qApp.quit()
  1924. def save_defaults(self, silent=False):
  1925. """
  1926. Saves application default options
  1927. ``self.defaults`` to current_defaults.FlatConfig.
  1928. :return: None
  1929. """
  1930. self.report_usage("save_defaults")
  1931. # Read options from file
  1932. try:
  1933. f = open(self.data_path + "/current_defaults.FlatConfig")
  1934. defaults_file_content = f.read()
  1935. f.close()
  1936. except:
  1937. e = sys.exc_info()[0]
  1938. App.log.error("Could not load defaults file.")
  1939. App.log.error(str(e))
  1940. self.inform.emit("[error_notcl] Could not load defaults file.")
  1941. return
  1942. try:
  1943. defaults = json.loads(defaults_file_content)
  1944. except:
  1945. e = sys.exc_info()[0]
  1946. App.log.error("Failed to parse defaults file.")
  1947. App.log.error(str(e))
  1948. self.inform.emit("[error_notcl] Failed to parse defaults file.")
  1949. return
  1950. # Update options
  1951. self.defaults_read_form()
  1952. defaults.update(self.defaults)
  1953. self.propagate_defaults(silent=True)
  1954. # Save update options
  1955. try:
  1956. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  1957. json.dump(defaults, f)
  1958. f.close()
  1959. except:
  1960. self.inform.emit("[error_notcl] Failed to write defaults to file.")
  1961. return
  1962. # Save the toolbar view
  1963. tb_status = 0
  1964. if self.ui.toolbarfile.isVisible():
  1965. tb_status += 1
  1966. if self.ui.toolbargeo.isVisible():
  1967. tb_status += 2
  1968. if self.ui.toolbarview.isVisible():
  1969. tb_status += 4
  1970. if self.ui.toolbartools.isVisible():
  1971. tb_status += 8
  1972. if self.ui.snap_toolbar.isVisible():
  1973. tb_status += 16
  1974. self.defaults["global_toolbar_view"] = tb_status
  1975. if not silent:
  1976. self.inform.emit("[success]Defaults saved.")
  1977. def save_factory_defaults(self, silent=False):
  1978. """
  1979. Saves application factory default options
  1980. ``self.defaults`` to factory_defaults.FlatConfig.
  1981. It's a one time job done just after the first install.
  1982. :return: None
  1983. """
  1984. self.report_usage("save_factory_defaults")
  1985. # Read options from file
  1986. try:
  1987. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  1988. factory_defaults_file_content = f_f_def.read()
  1989. f_f_def.close()
  1990. except:
  1991. e = sys.exc_info()[0]
  1992. App.log.error("Could not load factory defaults file.")
  1993. App.log.error(str(e))
  1994. self.inform.emit("[error_notcl] Could not load factory defaults file.")
  1995. return
  1996. try:
  1997. factory_defaults = json.loads(factory_defaults_file_content)
  1998. except:
  1999. e = sys.exc_info()[0]
  2000. App.log.error("Failed to parse factory defaults file.")
  2001. App.log.error(str(e))
  2002. self.inform.emit("[error_notcl] Failed to parse factory defaults file.")
  2003. return
  2004. # Update options
  2005. self.defaults_read_form()
  2006. factory_defaults.update(self.defaults)
  2007. self.propagate_defaults(silent=True)
  2008. # Save update options
  2009. try:
  2010. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2011. json.dump(factory_defaults, f_f_def_s)
  2012. f_f_def_s.close()
  2013. except:
  2014. self.inform.emit("[error_notcl] Failed to write factory defaults to file.")
  2015. return
  2016. if silent is False:
  2017. self.inform.emit("Factory defaults saved.")
  2018. def final_save(self):
  2019. if self.collection.get_list():
  2020. msgbox = QtWidgets.QMessageBox()
  2021. # msgbox.setText("<B>Save changes ...</B>")
  2022. msgbox.setText("There are files/objects opened in FlatCAM. "
  2023. "\n"
  2024. "Do you want to Save the project?")
  2025. msgbox.setWindowTitle("Save changes")
  2026. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2027. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2028. QtWidgets.QMessageBox.Cancel)
  2029. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2030. response = msgbox.exec_()
  2031. if response == QtWidgets.QMessageBox.Yes:
  2032. self.on_file_saveprojectas(thread=False)
  2033. elif response == QtWidgets.QMessageBox.Cancel:
  2034. self.should_we_quit = False
  2035. return
  2036. self.save_defaults()
  2037. log.debug("Application defaults saved ... Exit event.")
  2038. def on_toggle_shell(self):
  2039. """
  2040. toggle shell if is visible close it if closed open it
  2041. :return:
  2042. """
  2043. if self.ui.shell_dock.isVisible():
  2044. self.ui.shell_dock.hide()
  2045. else:
  2046. self.ui.shell_dock.show()
  2047. def on_edit_join(self, name=None):
  2048. """
  2049. Callback for Edit->Join. Joins the selected geometry objects into
  2050. a new one.
  2051. :return: None
  2052. """
  2053. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2054. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2055. tooldias = []
  2056. geo_type_list = []
  2057. objs = self.collection.get_selected()
  2058. for obj in objs:
  2059. geo_type_list.append(obj.multigeo)
  2060. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2061. if len(set(geo_type_list)) != 1:
  2062. self.inform.emit("[error] Failed join. The Geometry objects are of different types.\n"
  2063. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2064. "convert from one to another and retry joining \n"
  2065. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2066. "the result may not be what was expected. \n"
  2067. "Check the generated GCODE.")
  2068. return
  2069. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2070. if True in geo_type_list:
  2071. def initialize(obj, app):
  2072. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2073. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2074. for v in obj.tools.values():
  2075. v['data']['name'] = obj_name_multi
  2076. self.new_object("geometry", obj_name_multi, initialize)
  2077. else:
  2078. def initialize(obj, app):
  2079. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2080. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2081. for v in obj.tools.values():
  2082. v['data']['name'] = obj_name_single
  2083. self.new_object("geometry", obj_name_single, initialize)
  2084. def on_edit_join_exc(self):
  2085. """
  2086. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2087. a new one.
  2088. :return: None
  2089. """
  2090. objs = self.collection.get_selected()
  2091. for obj in objs:
  2092. if not isinstance(obj, FlatCAMExcellon):
  2093. self.inform.emit("[error_notcl]Failed. Excellon joining works only on Excellon objects.")
  2094. return
  2095. def initialize(obj, app):
  2096. FlatCAMExcellon.merge(objs, obj)
  2097. self.new_object("excellon", 'Combo_Excellon', initialize)
  2098. def on_edit_join_grb(self):
  2099. """
  2100. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2101. a new one.
  2102. :return: None
  2103. """
  2104. objs = self.collection.get_selected()
  2105. for obj in objs:
  2106. if not isinstance(obj, FlatCAMGerber):
  2107. self.inform.emit("[error_notcl]Failed. Gerber joining works only on Gerber objects.")
  2108. return
  2109. def initialize(obj, app):
  2110. FlatCAMGerber.merge(objs, obj)
  2111. self.new_object("gerber", 'Combo_Gerber', initialize)
  2112. def on_convert_singlegeo_to_multigeo(self):
  2113. obj = self.collection.get_active()
  2114. if obj is None:
  2115. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2116. return
  2117. if not isinstance(obj, FlatCAMGeometry):
  2118. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2119. return
  2120. obj.multigeo = True
  2121. for tooluid, dict_value in obj.tools.items():
  2122. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2123. if not isinstance(obj.solid_geometry, list):
  2124. obj.solid_geometry = [obj.solid_geometry]
  2125. obj.solid_geometry[:] = []
  2126. obj.plot()
  2127. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2128. def on_convert_multigeo_to_singlegeo(self):
  2129. obj = self.collection.get_active()
  2130. if obj is None:
  2131. self.inform.emit("[error_notcl]Failed. Select a Geometry Object and try again.")
  2132. return
  2133. if not isinstance(obj, FlatCAMGeometry):
  2134. self.inform.emit("[error_notcl]Expected a FlatCAMGeometry, got %s" % type(obj))
  2135. return
  2136. obj.multigeo = False
  2137. total_solid_geometry = []
  2138. for tooluid, dict_value in obj.tools.items():
  2139. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2140. # clear the original geometry
  2141. dict_value['solid_geometry'][:] = []
  2142. obj.solid_geometry = deepcopy(total_solid_geometry)
  2143. obj.plot()
  2144. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2145. def on_options_dict_change(self, field):
  2146. self.options_write_form_field(field)
  2147. if field == "units":
  2148. self.set_screen_units(self.options['units'])
  2149. def on_defaults_dict_change(self, field):
  2150. self.defaults_write_form_field(field)
  2151. def set_screen_units(self, units):
  2152. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2153. def on_toggle_units(self):
  2154. """
  2155. Callback for the Units radio-button change in the Options tab.
  2156. Changes the application's default units or the current project's units.
  2157. If changing the project's units, the change propagates to all of
  2158. the objects in the project.
  2159. :return: None
  2160. """
  2161. self.report_usage("on_toggle_units")
  2162. if self.toggle_units_ignore:
  2163. return
  2164. # If option is the same, then ignore
  2165. if self.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2166. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2167. return
  2168. # Options to scale
  2169. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2170. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2171. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2172. 'gerber_noncoppermargin','gerber_bboxmargin',
  2173. 'excellon_drillz', "excellon_toolchangexy",
  2174. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2175. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2176. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2177. 'geometry_cnctooldia', 'geometry_painttooldia', 'geometry_paintoverlap', 'geometry_toolchangexy',
  2178. 'geometry_toolchangez',
  2179. 'geometry_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2180. def scale_options(sfactor):
  2181. for dim in dimensions:
  2182. if dim == 'excellon_toolchangexy':
  2183. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2184. coords_xy[0] *= sfactor
  2185. coords_xy[1] *= sfactor
  2186. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2187. elif dim == 'geometry_toolchangexy':
  2188. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2189. coords_xy[0] *= sfactor
  2190. coords_xy[1] *= sfactor
  2191. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2192. else:
  2193. self.options[dim] *= sfactor
  2194. # The scaling factor depending on choice of units.
  2195. factor = 1/25.4
  2196. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2197. factor = 25.4
  2198. # Changing project units. Warn user.
  2199. msgbox = QtWidgets.QMessageBox()
  2200. msgbox.setText("<B>Change project units ...</B>")
  2201. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2202. "properties of all objects to be scaled accordingly. Continue?")
  2203. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2204. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2205. response = msgbox.exec_()
  2206. if response == QtWidgets.QMessageBox.Ok:
  2207. self.options_read_form()
  2208. scale_options(factor)
  2209. self.options_write_form()
  2210. # change this only if the workspace is active
  2211. if self.defaults['global_workspace'] is True:
  2212. self.plotcanvas.draw_workspace()
  2213. # adjust the grid values on the main toolbar
  2214. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2215. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2216. for obj in self.collection.get_list():
  2217. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  2218. obj.convert_units(units)
  2219. # make that the properties stored in the object are also updated
  2220. self.object_changed.emit(obj)
  2221. obj.build_ui()
  2222. current = self.collection.get_active()
  2223. if current is not None:
  2224. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2225. if not isinstance(current, FlatCAMGeometry):
  2226. current.to_form()
  2227. self.plot_all()
  2228. else:
  2229. # Undo toggling
  2230. self.toggle_units_ignore = True
  2231. if self.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2232. self.general_options_form.general_app_group.units_radio.set_value('IN')
  2233. else:
  2234. self.general_options_form.general_app_group.units_radio.set_value('MM')
  2235. self.toggle_units_ignore = False
  2236. self.options_read_form()
  2237. self.inform.emit("Converted units to %s" % self.options["units"])
  2238. #self.ui.units_label.setText("[" + self.options["units"] + "]")
  2239. self.set_screen_units(self.options["units"])
  2240. def on_toggle_units_click(self):
  2241. if self.options["units"] == 'MM':
  2242. self.general_options_form.general_app_group.units_radio.set_value("IN")
  2243. else:
  2244. self.general_options_form.general_app_group.units_radio.set_value("MM")
  2245. self.on_toggle_units()
  2246. def on_language_apply(self):
  2247. # TODO: apply the language
  2248. # app restart section
  2249. pass
  2250. def on_toggle_axis(self):
  2251. if self.toggle_axis is False:
  2252. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2253. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2254. self.plotcanvas.redraw()
  2255. self.toggle_axis = True
  2256. else:
  2257. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2258. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2259. self.plotcanvas.redraw()
  2260. self.toggle_axis = False
  2261. def on_toggle_grid(self):
  2262. self.ui.grid_snap_btn.trigger()
  2263. def on_options_combo_change(self, sel):
  2264. """
  2265. Called when the combo box to choose between application defaults and
  2266. project option changes value. The corresponding variables are
  2267. copied to the UI.
  2268. :param sel: The option index that was chosen.
  2269. :return: None
  2270. """
  2271. # combo_sel = self.ui.notebook.combo_options.get_active()
  2272. App.log.debug("Options --> %s" % sel)
  2273. # form = [self.defaults_form, self.options_form][sel]
  2274. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2275. if sel == 0:
  2276. self.gen_form = self.general_defaults_form
  2277. self.ger_form = self.gerber_defaults_form
  2278. self.exc_form = self.excellon_defaults_form
  2279. self.geo_form = self.geometry_defaults_form
  2280. self.cnc_form = self.cncjob_defaults_form
  2281. self.tools_form = self.tools_defaults_form
  2282. elif sel == 1:
  2283. self.gen_form = self.general_options_form
  2284. self.ger_form = self.gerber_options_form
  2285. self.exc_form = self.excellon_options_form
  2286. self.geo_form = self.geometry_options_form
  2287. self.cnc_form = self.cncjob_options_form
  2288. self.tools_form = self.tools_options_form
  2289. else:
  2290. return
  2291. try:
  2292. self.ui.general_scroll_area.takeWidget()
  2293. except:
  2294. self.log.debug("Nothing to remove")
  2295. self.ui.general_scroll_area.setWidget(self.gen_form)
  2296. self.gen_form.show()
  2297. try:
  2298. self.ui.gerber_scroll_area.takeWidget()
  2299. except:
  2300. self.log.debug("Nothing to remove")
  2301. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2302. self.ger_form.show()
  2303. try:
  2304. self.ui.excellon_scroll_area.takeWidget()
  2305. except:
  2306. self.log.debug("Nothing to remove")
  2307. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2308. self.exc_form.show()
  2309. try:
  2310. self.ui.geometry_scroll_area.takeWidget()
  2311. except:
  2312. self.log.debug("Nothing to remove")
  2313. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2314. self.geo_form.show()
  2315. try:
  2316. self.ui.cncjob_scroll_area.takeWidget()
  2317. except:
  2318. self.log.debug("Nothing to remove")
  2319. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2320. self.cnc_form.show()
  2321. try:
  2322. self.ui.tools_scroll_area.takeWidget()
  2323. except:
  2324. self.log.debug("Nothing to remove")
  2325. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2326. self.tools_form.show()
  2327. self.log.debug("Finished GUI form initialization.")
  2328. # self.options2form()
  2329. def on_excellon_defaults_button(self):
  2330. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2331. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2332. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2333. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2334. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2335. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2336. log.debug("Excellon app defaults loaded ...")
  2337. def on_excellon_options_button(self):
  2338. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2339. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2340. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2341. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2342. self.options_form_fields["excellon_zeros"].set_value('L')
  2343. self.options_form_fields["excellon_units"].set_value('INCH')
  2344. log.debug("Excellon options defaults loaded ...")
  2345. # Setting plot colors handlers
  2346. def on_pf_color_entry(self):
  2347. self.defaults['global_plot_fill'] = self.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2348. self.defaults['global_plot_fill'][7:9]
  2349. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2350. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2351. def on_pf_color_button(self):
  2352. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2353. c_dialog = QtWidgets.QColorDialog()
  2354. plot_fill_color = c_dialog.getColor(initial=current_color)
  2355. if plot_fill_color.isValid() is False:
  2356. return
  2357. self.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2358. "background-color:%s" % str(plot_fill_color.name()))
  2359. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2360. self.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2361. self.defaults['global_plot_fill'] = new_val
  2362. def on_pf_color_spinner(self):
  2363. spinner_value = self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2364. self.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2365. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2366. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2367. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2368. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2369. def on_pf_color_slider(self):
  2370. slider_value = self.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2371. self.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2372. def on_pl_color_entry(self):
  2373. self.defaults['global_plot_line'] = self.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2374. self.defaults['global_plot_line'][7:9]
  2375. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2376. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2377. def on_pl_color_button(self):
  2378. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2379. # print(current_color)
  2380. c_dialog = QtWidgets.QColorDialog()
  2381. plot_line_color = c_dialog.getColor(initial=current_color)
  2382. if plot_line_color.isValid() is False:
  2383. return
  2384. self.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2385. "background-color:%s" % str(plot_line_color.name()))
  2386. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2387. self.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2388. self.defaults['global_plot_line'] = new_val_line
  2389. # Setting selection colors (left - right) handlers
  2390. def on_sf_color_entry(self):
  2391. self.defaults['global_sel_fill'] = self.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2392. self.defaults['global_sel_fill'][7:9]
  2393. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2394. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2395. def on_sf_color_button(self):
  2396. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2397. c_dialog = QtWidgets.QColorDialog()
  2398. plot_fill_color = c_dialog.getColor(initial=current_color)
  2399. if plot_fill_color.isValid() is False:
  2400. return
  2401. self.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2402. "background-color:%s" % str(plot_fill_color.name()))
  2403. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2404. self.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2405. self.defaults['global_sel_fill'] = new_val
  2406. def on_sf_color_spinner(self):
  2407. spinner_value = self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2408. self.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2409. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2410. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2411. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2412. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2413. def on_sf_color_slider(self):
  2414. slider_value = self.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2415. self.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2416. def on_sl_color_entry(self):
  2417. self.defaults['global_sel_line'] = self.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2418. self.defaults['global_sel_line'][7:9]
  2419. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2420. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2421. def on_sl_color_button(self):
  2422. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2423. c_dialog = QtWidgets.QColorDialog()
  2424. plot_line_color = c_dialog.getColor(initial=current_color)
  2425. if plot_line_color.isValid() is False:
  2426. return
  2427. self.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2428. "background-color:%s" % str(plot_line_color.name()))
  2429. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2430. self.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2431. self.defaults['global_sel_line'] = new_val_line
  2432. # Setting selection colors (right - left) handlers
  2433. def on_alt_sf_color_entry(self):
  2434. self.defaults['global_alt_sel_fill'] = self.general_defaults_form.general_gui_group \
  2435. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2436. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2437. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2438. def on_alt_sf_color_button(self):
  2439. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2440. c_dialog = QtWidgets.QColorDialog()
  2441. plot_fill_color = c_dialog.getColor(initial=current_color)
  2442. if plot_fill_color.isValid() is False:
  2443. return
  2444. self.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2445. "background-color:%s" % str(plot_fill_color.name()))
  2446. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2447. self.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2448. self.defaults['global_alt_sel_fill'] = new_val
  2449. def on_alt_sf_color_spinner(self):
  2450. spinner_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2451. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2452. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2453. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2454. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2455. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2456. def on_alt_sf_color_slider(self):
  2457. slider_value = self.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2458. self.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2459. def on_alt_sl_color_entry(self):
  2460. self.defaults['global_alt_sel_line'] = self.general_defaults_form.general_gui_group \
  2461. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2462. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2463. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2464. def on_alt_sl_color_button(self):
  2465. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2466. c_dialog = QtWidgets.QColorDialog()
  2467. plot_line_color = c_dialog.getColor(initial=current_color)
  2468. if plot_line_color.isValid() is False:
  2469. return
  2470. self.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2471. "background-color:%s" % str(plot_line_color.name()))
  2472. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2473. self.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2474. self.defaults['global_alt_sel_line'] = new_val_line
  2475. # Setting Editor colors
  2476. def on_draw_color_entry(self):
  2477. self.defaults['global_draw_color'] = self.general_defaults_form.general_gui_group \
  2478. .draw_color_entry.get_value()
  2479. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2480. "background-color:%s" % str(self.defaults['global_draw_color']))
  2481. def on_draw_color_button(self):
  2482. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2483. c_dialog = QtWidgets.QColorDialog()
  2484. draw_color = c_dialog.getColor(initial=current_color)
  2485. if draw_color.isValid() is False:
  2486. return
  2487. self.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2488. "background-color:%s" % str(draw_color.name()))
  2489. new_val = str(draw_color.name())
  2490. self.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2491. self.defaults['global_draw_color'] = new_val
  2492. def on_sel_draw_color_entry(self):
  2493. self.defaults['global_sel_draw_color'] = self.general_defaults_form.general_gui_group \
  2494. .sel_draw_color_entry.get_value()
  2495. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2496. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2497. def on_sel_draw_color_button(self):
  2498. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2499. c_dialog = QtWidgets.QColorDialog()
  2500. sel_draw_color = c_dialog.getColor(initial=current_color)
  2501. if sel_draw_color.isValid() is False:
  2502. return
  2503. self.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2504. "background-color:%s" % str(sel_draw_color.name()))
  2505. new_val_sel = str(sel_draw_color.name())
  2506. self.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2507. self.defaults['global_sel_draw_color'] = new_val_sel
  2508. def on_workspace_modified(self):
  2509. self.save_defaults(silent=True)
  2510. self.plotcanvas.draw_workspace()
  2511. def on_workspace(self):
  2512. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2513. self.plotcanvas.restore_workspace()
  2514. else:
  2515. self.plotcanvas.delete_workspace()
  2516. self.save_defaults(silent=True)
  2517. def on_workspace_menu(self):
  2518. if self.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2519. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2520. else:
  2521. self.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2522. self.on_workspace()
  2523. def on_save_button(self):
  2524. self.save_defaults(silent=False)
  2525. # load the defaults so they are updated into the app
  2526. self.load_defaults(filename='current_defaults')
  2527. # Re-fresh project options
  2528. self.on_options_app2project()
  2529. def handleOpen(self):
  2530. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2531. "All Files (*.*)"
  2532. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2533. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2534. if path:
  2535. file = QtCore.QFile(path)
  2536. if file.open(QtCore.QIODevice.ReadOnly):
  2537. stream = QtCore.QTextStream(file)
  2538. self.gcode_edited = stream.readAll()
  2539. self.ui.code_editor.setPlainText(self.gcode_edited)
  2540. file.close()
  2541. def handlePrint(self):
  2542. dialog = QtPrintSupport.QPrintDialog()
  2543. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  2544. self.ui.code_editor.document().print_(dialog.printer())
  2545. def handlePreview(self):
  2546. dialog = QtPrintSupport.QPrintPreviewDialog()
  2547. dialog.paintRequested.connect(self.ui.code_editor.print_)
  2548. dialog.exec_()
  2549. def handleTextChanged(self):
  2550. # enable = not self.ui.code_editor.document().isEmpty()
  2551. # self.ui.buttonPrint.setEnabled(enable)
  2552. # self.ui.buttonPreview.setEnabled(enable)
  2553. pass
  2554. def handleSaveGCode(self):
  2555. _filter_ = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2556. "All Files (*.*)"
  2557. try:
  2558. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  2559. caption="Export G-Code ...", directory=self.defaults["global_last_folder"], filter=_filter_)[0])
  2560. except TypeError:
  2561. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  2562. try:
  2563. my_gcode = self.ui.code_editor.toPlainText()
  2564. with open(filename, 'w') as f:
  2565. for line in my_gcode:
  2566. f.write(line)
  2567. except FileNotFoundError:
  2568. self.inform.emit("[WARNING] No such file or directory")
  2569. return
  2570. # Just for adding it to the recent files list.
  2571. self.file_opened.emit("cncjob", filename)
  2572. self.file_saved.emit("cncjob", filename)
  2573. self.inform.emit("Saved to: " + filename)
  2574. def handleFindGCode(self):
  2575. flags = QtGui.QTextDocument.FindCaseSensitively
  2576. text_to_be_found = self.ui.entryFind.get_value()
  2577. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  2578. if r is False:
  2579. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2580. def handleReplaceGCode(self):
  2581. old = self.ui.entryFind.get_value()
  2582. new = self.ui.entryReplace.get_value()
  2583. if self.ui.sel_all_cb.isChecked():
  2584. while True:
  2585. cursor = self.ui.code_editor.textCursor()
  2586. cursor.beginEditBlock()
  2587. flags = QtGui.QTextDocument.FindCaseSensitively
  2588. # self.ui.editor is the QPlainTextEdit
  2589. r = self.ui.code_editor.find(str(old), flags)
  2590. if r:
  2591. qc = self.ui.code_editor.textCursor()
  2592. if qc.hasSelection():
  2593. qc.insertText(new)
  2594. else:
  2595. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  2596. break
  2597. # Mark end of undo block
  2598. cursor.endEditBlock()
  2599. else:
  2600. cursor = self.ui.code_editor.textCursor()
  2601. cursor.beginEditBlock()
  2602. qc = self.ui.code_editor.textCursor()
  2603. if qc.hasSelection():
  2604. qc.insertText(new)
  2605. # Mark end of undo block
  2606. cursor.endEditBlock()
  2607. def on_new_geometry(self):
  2608. def initialize(obj, self):
  2609. obj.multitool = False
  2610. self.new_object('geometry', 'new_g', initialize)
  2611. self.plot_all()
  2612. def on_delete(self):
  2613. """
  2614. Delete the currently selected FlatCAMObjs.
  2615. :return: None
  2616. """
  2617. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  2618. # a geometry object before we update it.
  2619. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  2620. if self.collection.get_active():
  2621. self.log.debug("on_delete()")
  2622. self.report_usage("on_delete")
  2623. while (self.collection.get_active()):
  2624. self.delete_first_selected()
  2625. self.inform.emit("Object(s) deleted ...")
  2626. # make sure that the selection shape is deleted, too
  2627. self.delete_selection_shape()
  2628. else:
  2629. self.inform.emit("Failed. No object(s) selected...")
  2630. else:
  2631. self.inform.emit("Save the work in Editor and try again ...")
  2632. def on_set_origin(self):
  2633. """
  2634. Set the origin to the left mouse click position
  2635. :return: None
  2636. """
  2637. #display the message for the user
  2638. #and ask him to click on the desired position
  2639. self.inform.emit('Click to set the origin ...')
  2640. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  2641. def on_jump_to(self):
  2642. """
  2643. Jump to a location by setting the mouse cursor location
  2644. :return:
  2645. """
  2646. dia_box = Dialog_box(title="Jump to Coordinates", label="Enter the coordinates in format X,Y:")
  2647. if dia_box.ok is True:
  2648. try:
  2649. location = eval(dia_box.location)
  2650. if not isinstance(location, tuple):
  2651. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  2652. return
  2653. except:
  2654. return
  2655. else:
  2656. return
  2657. self.plotcanvas.fit_center(loc=location)
  2658. cursor = QtGui.QCursor()
  2659. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  2660. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  2661. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  2662. self.inform.emit("Done.")
  2663. def on_copy_object(self):
  2664. def initialize(obj_init, app):
  2665. obj_init.solid_geometry = obj.solid_geometry
  2666. try:
  2667. if obj.tools:
  2668. obj_init.tools = obj.tools
  2669. except Exception as e:
  2670. log.debug("on_copy_object() --> %s" % str(e))
  2671. def initialize_excellon(obj_init, app):
  2672. obj_init.tools = obj.tools
  2673. # drills are offset, so they need to be deep copied
  2674. obj_init.drills = deepcopy(obj.drills)
  2675. # slots are offset, so they need to be deep copied
  2676. obj_init.slots = deepcopy(obj.slots)
  2677. obj_init.create_geometry()
  2678. for obj in self.collection.get_selected():
  2679. obj_name = obj.options["name"]
  2680. try:
  2681. if isinstance(obj, FlatCAMExcellon):
  2682. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  2683. elif isinstance(obj,FlatCAMGerber):
  2684. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  2685. elif isinstance(obj,FlatCAMGeometry):
  2686. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  2687. except Exception as e:
  2688. return "Operation failed: %s" % str(e)
  2689. def on_copy_object2(self, custom_name):
  2690. def initialize_geometry(obj_init, app):
  2691. obj_init.solid_geometry = obj.solid_geometry
  2692. try:
  2693. if obj.tools:
  2694. obj_init.tools = obj.tools
  2695. except Exception as e:
  2696. log.debug("on_copy_object2() --> %s" % str(e))
  2697. def initialize_gerber(obj_init, app):
  2698. obj_init.solid_geometry = obj.solid_geometry
  2699. obj_init.apertures = deepcopy(obj.apertures)
  2700. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  2701. def initialize_excellon(obj_init, app):
  2702. obj_init.tools = obj.tools
  2703. # drills are offset, so they need to be deep copied
  2704. obj_init.drills = deepcopy(obj.drills)
  2705. # slots are offset, so they need to be deep copied
  2706. obj_init.slots = deepcopy(obj.slots)
  2707. obj_init.create_geometry()
  2708. for obj in self.collection.get_selected():
  2709. obj_name = obj.options["name"]
  2710. try:
  2711. if isinstance(obj, FlatCAMExcellon):
  2712. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  2713. elif isinstance(obj,FlatCAMGerber):
  2714. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  2715. elif isinstance(obj,FlatCAMGeometry):
  2716. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  2717. except Exception as e:
  2718. return "Operation failed: %s" % str(e)
  2719. def on_rename_object(self, text):
  2720. named_obj = self.collection.get_active()
  2721. for obj in named_obj:
  2722. if obj is list:
  2723. self.on_rename_object(text)
  2724. else:
  2725. try:
  2726. obj.options['name'] = text
  2727. except:
  2728. log.warning("Could not rename the object in the list")
  2729. def on_copy_object_as_geometry(self):
  2730. def initialize(obj_init, app):
  2731. obj_init.solid_geometry = obj.solid_geometry
  2732. if obj.tools:
  2733. obj_init.tools = obj.tools
  2734. def initialize_excellon(obj, app):
  2735. objs = self.collection.get_selected()
  2736. FlatCAMGeometry.merge(objs, obj)
  2737. for obj in self.collection.get_selected():
  2738. obj_name = obj.options["name"]
  2739. try:
  2740. if isinstance(obj, FlatCAMExcellon):
  2741. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  2742. else:
  2743. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  2744. except Exception as e:
  2745. return "Operation failed: %s" % str(e)
  2746. def on_set_zero_click(self, event):
  2747. #this function will be available only for mouse left click
  2748. pos =[]
  2749. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  2750. if event.button == 1:
  2751. if self.grid_status() == True:
  2752. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  2753. else:
  2754. pos = pos_canvas
  2755. x = 0 - pos[0]
  2756. y = 0 - pos[1]
  2757. for obj in self.collection.get_list():
  2758. obj.offset((x,y))
  2759. self.object_changed.emit(obj)
  2760. # obj.plot()
  2761. self.plot_all()
  2762. self.inform.emit('[success] Origin set ...')
  2763. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  2764. def on_selectall(self):
  2765. # delete the possible selection box around a possible selected object
  2766. self.delete_selection_shape()
  2767. for name in self.collection.get_names():
  2768. self.collection.set_active(name)
  2769. curr_sel_obj = self.collection.get_by_name(name)
  2770. # create the selection box around the selected object
  2771. self.draw_selection_shape(curr_sel_obj)
  2772. def on_preferences(self):
  2773. # add the tab if it was closed
  2774. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  2775. # delete the absolute and relative position and messages in the infobar
  2776. self.ui.position_label.setText("")
  2777. self.ui.rel_position_label.setText("")
  2778. # Switch plot_area to preferences page
  2779. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  2780. self.ui.show()
  2781. def on_flipy(self):
  2782. obj_list = self.collection.get_selected()
  2783. xminlist = []
  2784. yminlist = []
  2785. xmaxlist = []
  2786. ymaxlist = []
  2787. if not obj_list:
  2788. self.inform.emit("[warning_notcl] No object selected.")
  2789. msg = "Please Select an object to flip!"
  2790. warningbox = QtWidgets.QMessageBox()
  2791. warningbox.setText(msg)
  2792. warningbox.setWindowTitle("Warning ...")
  2793. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2794. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2795. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2796. warningbox.exec_()
  2797. else:
  2798. try:
  2799. # first get a bounding box to fit all
  2800. for obj in obj_list:
  2801. xmin, ymin, xmax, ymax = obj.bounds()
  2802. xminlist.append(xmin)
  2803. yminlist.append(ymin)
  2804. xmaxlist.append(xmax)
  2805. ymaxlist.append(ymax)
  2806. # get the minimum x,y and maximum x,y for all objects selected
  2807. xminimal = min(xminlist)
  2808. yminimal = min(yminlist)
  2809. xmaximal = max(xmaxlist)
  2810. ymaximal = max(ymaxlist)
  2811. px = 0.5 * (xminimal + xmaximal)
  2812. py = 0.5 * (yminimal + ymaximal)
  2813. # execute mirroring
  2814. for obj in obj_list:
  2815. obj.mirror('X', [px, py])
  2816. obj.plot()
  2817. self.object_changed.emit(obj)
  2818. except Exception as e:
  2819. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2820. return
  2821. def on_flipx(self):
  2822. obj_list = self.collection.get_selected()
  2823. xminlist = []
  2824. yminlist = []
  2825. xmaxlist = []
  2826. ymaxlist = []
  2827. if not obj_list:
  2828. self.inform.emit("[warning_notcl] No object selected.")
  2829. msg = "Please Select an object to flip!"
  2830. warningbox = QtWidgets.QMessageBox()
  2831. warningbox.setText(msg)
  2832. warningbox.setWindowTitle("Warning ...")
  2833. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2834. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2835. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2836. warningbox.exec_()
  2837. else:
  2838. try:
  2839. # first get a bounding box to fit all
  2840. for obj in obj_list:
  2841. xmin, ymin, xmax, ymax = obj.bounds()
  2842. xminlist.append(xmin)
  2843. yminlist.append(ymin)
  2844. xmaxlist.append(xmax)
  2845. ymaxlist.append(ymax)
  2846. # get the minimum x,y and maximum x,y for all objects selected
  2847. xminimal = min(xminlist)
  2848. yminimal = min(yminlist)
  2849. xmaximal = max(xmaxlist)
  2850. ymaximal = max(ymaxlist)
  2851. px = 0.5 * (xminimal + xmaximal)
  2852. py = 0.5 * (yminimal + ymaximal)
  2853. # execute mirroring
  2854. for obj in obj_list:
  2855. obj.mirror('Y', [px, py])
  2856. obj.plot()
  2857. self.object_changed.emit(obj)
  2858. except Exception as e:
  2859. self.inform.emit("[error_notcl] Due of %s, Flip action was not executed." % str(e))
  2860. return
  2861. def on_rotate(self, silent=False, preset=None):
  2862. obj_list = self.collection.get_selected()
  2863. xminlist = []
  2864. yminlist = []
  2865. xmaxlist = []
  2866. ymaxlist = []
  2867. if not obj_list:
  2868. self.inform.emit("[warning_notcl] No object selected.")
  2869. msg = "Please Select an object to rotate!"
  2870. warningbox = QtWidgets.QMessageBox()
  2871. warningbox.setText(msg)
  2872. warningbox.setWindowTitle("Warning ...")
  2873. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2874. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2875. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2876. warningbox.exec_()
  2877. else:
  2878. if silent is False:
  2879. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2880. min=-360, max=360, decimals=3)
  2881. num, ok = rotatebox.get_value()
  2882. else:
  2883. num = preset
  2884. ok = True
  2885. if ok:
  2886. try:
  2887. # first get a bounding box to fit all
  2888. for obj in obj_list:
  2889. xmin, ymin, xmax, ymax = obj.bounds()
  2890. xminlist.append(xmin)
  2891. yminlist.append(ymin)
  2892. xmaxlist.append(xmax)
  2893. ymaxlist.append(ymax)
  2894. # get the minimum x,y and maximum x,y for all objects selected
  2895. xminimal = min(xminlist)
  2896. yminimal = min(yminlist)
  2897. xmaximal = max(xmaxlist)
  2898. ymaximal = max(ymaxlist)
  2899. px = 0.5 * (xminimal + xmaximal)
  2900. py = 0.5 * (yminimal + ymaximal)
  2901. for sel_obj in obj_list:
  2902. sel_obj.rotate(-num, point=(px, py))
  2903. sel_obj.plot()
  2904. self.object_changed.emit(sel_obj)
  2905. except Exception as e:
  2906. self.inform.emit("[error_notcl] Due of %s, rotation movement was not executed." % str(e))
  2907. return
  2908. def on_skewx(self):
  2909. obj_list = self.collection.get_selected()
  2910. xminlist = []
  2911. yminlist = []
  2912. if not obj_list:
  2913. self.inform.emit("[warning_notcl] No object selected.")
  2914. msg = "Please Select an object to skew/shear!"
  2915. warningbox = QtWidgets.QMessageBox()
  2916. warningbox.setText(msg)
  2917. warningbox.setWindowTitle("Warning ...")
  2918. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2919. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2920. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2921. warningbox.exec_()
  2922. else:
  2923. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2924. min=-360, max=360, decimals=3)
  2925. num, ok = skewxbox.get_value()
  2926. if ok:
  2927. # first get a bounding box to fit all
  2928. for obj in obj_list:
  2929. xmin, ymin, xmax, ymax = obj.bounds()
  2930. xminlist.append(xmin)
  2931. yminlist.append(ymin)
  2932. # get the minimum x,y and maximum x,y for all objects selected
  2933. xminimal = min(xminlist)
  2934. yminimal = min(yminlist)
  2935. for obj in obj_list:
  2936. obj.skew(num, 0, point=(xminimal, yminimal))
  2937. obj.plot()
  2938. self.object_changed.emit(obj)
  2939. def on_skewy(self):
  2940. obj_list = self.collection.get_selected()
  2941. xminlist = []
  2942. yminlist = []
  2943. if not obj_list:
  2944. self.inform.emit("[warning_notcl] No object selected.")
  2945. msg = "Please Select an object to skew/shear!"
  2946. warningbox = QtWidgets.QMessageBox()
  2947. warningbox.setText(msg)
  2948. warningbox.setWindowTitle("Warning ...")
  2949. warningbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  2950. warningbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  2951. warningbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2952. warningbox.exec_()
  2953. else:
  2954. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  2955. min=-360, max=360, decimals=3)
  2956. num, ok = skewybox.get_value()
  2957. if ok:
  2958. # first get a bounding box to fit all
  2959. for obj in obj_list:
  2960. xmin, ymin, xmax, ymax = obj.bounds()
  2961. xminlist.append(xmin)
  2962. yminlist.append(ymin)
  2963. # get the minimum x,y and maximum x,y for all objects selected
  2964. xminimal = min(xminlist)
  2965. yminimal = min(yminlist)
  2966. for obj in obj_list:
  2967. obj.skew(0, num, point=(xminimal, yminimal))
  2968. obj.plot()
  2969. self.object_changed.emit(obj)
  2970. def delete_first_selected(self):
  2971. # Keep this for later
  2972. try:
  2973. name = self.collection.get_active().options["name"]
  2974. except AttributeError:
  2975. self.log.debug("Nothing selected for deletion")
  2976. return
  2977. # Remove plot
  2978. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  2979. # self.plotcanvas.auto_adjust_axes()
  2980. # Clear form
  2981. self.setup_component_editor()
  2982. # Remove from dictionary
  2983. self.collection.delete_active()
  2984. self.inform.emit("Object deleted: %s" % name)
  2985. def on_plots_updated(self):
  2986. """
  2987. Callback used to report when the plots have changed.
  2988. Adjust axes and zooms to fit.
  2989. :return: None
  2990. """
  2991. # self.plotcanvas.auto_adjust_axes()
  2992. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  2993. self.on_zoom_fit(None)
  2994. # TODO: Rework toolbar 'clear', 'replot' functions
  2995. def on_toolbar_replot(self):
  2996. """
  2997. Callback for toolbar button. Re-plots all objects.
  2998. :return: None
  2999. """
  3000. self.report_usage("on_toolbar_replot")
  3001. self.log.debug("on_toolbar_replot()")
  3002. try:
  3003. self.collection.get_active().read_form()
  3004. except AttributeError:
  3005. self.log.debug("on_toolbar_replot(): AttributeError")
  3006. pass
  3007. self.plot_all()
  3008. def on_row_activated(self, index):
  3009. if index.isValid():
  3010. if index.internalPointer().parent_item != self.collection.root_item:
  3011. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3012. def on_zoom_fit(self, event):
  3013. """
  3014. Callback for zoom-out request. This can be either from the corresponding
  3015. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  3016. with axes limits from the geometry bounds of all objects.
  3017. :param event: Ignored.
  3018. :return: None
  3019. """
  3020. self.plotcanvas.fit_view()
  3021. def grid_status(self):
  3022. if self.ui.grid_snap_btn.isChecked():
  3023. return 1
  3024. else:
  3025. return 0
  3026. def on_key_over_plot(self, event):
  3027. """
  3028. Callback for the key pressed event when the canvas is focused. Keyboard
  3029. shortcuts are handled here. So far, these are the shortcuts:
  3030. ========== ============================================
  3031. Key Action
  3032. ========== ============================================
  3033. '1' Zoom-fit. Fits the axes limits to the data.
  3034. '2' Zoom-out.
  3035. '3' Zoom-in.
  3036. 'ctrl+m' Toggle on-off the measuring tool.
  3037. ========== ============================================
  3038. :param event: Ignored.
  3039. :return: None
  3040. """
  3041. self.key_modifiers = QtWidgets.QApplication.keyboardModifiers()
  3042. if self.key_modifiers == QtCore.Qt.ControlModifier:
  3043. if event.key == 'A':
  3044. self.on_selectall()
  3045. if event.key == 'C':
  3046. self.on_copy_object()
  3047. if event.key == 'E':
  3048. self.on_fileopenexcellon()
  3049. if event.key == 'G':
  3050. self.on_fileopengerber()
  3051. if event.key == 'N':
  3052. self.on_file_new_click()
  3053. if event.key == 'M':
  3054. self.measurement_tool.run()
  3055. if event.key == 'O':
  3056. self.on_file_openproject()
  3057. if event.key == 'S':
  3058. self.on_file_saveproject()
  3059. return
  3060. elif self.key_modifiers == QtCore.Qt.AltModifier:
  3061. # place holder for further shortcut key
  3062. if event.key == 'C':
  3063. self.calculator_tool.run()
  3064. if event.key == 'D':
  3065. self.dblsidedtool.run()
  3066. if event.key == 'L':
  3067. self.film_tool.run()
  3068. if event.key == 'N':
  3069. self.ncclear_tool.run()
  3070. if event.key == 'P':
  3071. self.paint_tool.run()
  3072. if event.key == 'R':
  3073. self.transform_tool.run()
  3074. if event.key == 'U':
  3075. self.cutout_tool.run()
  3076. if event.key == 'Z':
  3077. self.panelize_tool.run()
  3078. elif self.key_modifiers == QtCore.Qt.ShiftModifier:
  3079. # place holder for further shortcut key
  3080. if event.key == 'C':
  3081. self.on_copy_name()
  3082. # Toggle axis
  3083. if event.key == 'G':
  3084. self.on_toggle_axis()
  3085. # Open Preferences Window
  3086. if event.key == 'P':
  3087. self.on_preferences()
  3088. # Rotate Object by 90 degree CCW
  3089. if event.key == 'R':
  3090. self.on_rotate(silent=True, preset=-90)
  3091. # Run a Script
  3092. if event.key == 'S':
  3093. self.on_filerunscript()
  3094. # Toggle Workspace
  3095. if event.key == 'W':
  3096. self.on_workspace_menu()
  3097. # Skew on X axis
  3098. if event.key == 'X':
  3099. self.on_skewx()
  3100. # Skew on Y axis
  3101. if event.key == 'Y':
  3102. self.on_skewy()
  3103. return
  3104. else:
  3105. if event.key == 'F1':
  3106. webbrowser.open(self.manual_url)
  3107. return
  3108. if event.key == 'F2':
  3109. webbrowser.open(self.video_url)
  3110. return
  3111. if event.key == self.defaults['fit_key']: # 1
  3112. self.on_zoom_fit(None)
  3113. return
  3114. if event.key == self.defaults['zoom_out_key']: # 2
  3115. self.plotcanvas.zoom(1 / self.defaults['zoom_ratio'], self.mouse)
  3116. return
  3117. if event.key == self.defaults['zoom_in_key']: # 3
  3118. self.plotcanvas.zoom(self.defaults['zoom_ratio'], self.mouse)
  3119. return
  3120. if event.key == 'Delete':
  3121. self.on_delete()
  3122. return
  3123. if event.key == 'Space':
  3124. if self.collection.get_active() is not None:
  3125. self.collection.get_active().ui.plot_cb.toggle()
  3126. self.delete_selection_shape()
  3127. if event.key == 'E':
  3128. self.object2editor()
  3129. if event.key == self.defaults['grid_toggle_key']: # G
  3130. self.ui.grid_snap_btn.trigger()
  3131. if event.key == 'J':
  3132. self.on_jump_to()
  3133. if event.key == 'L':
  3134. self.new_excellon_object()
  3135. if event.key == 'M':
  3136. self.move_tool.toggle()
  3137. return
  3138. if event.key == 'N':
  3139. self.on_new_geometry()
  3140. if event.key == 'O':
  3141. self.on_set_origin()
  3142. if event.key == 'P':
  3143. self.properties_tool.run()
  3144. if event.key == 'Q':
  3145. self.on_toggle_units_click()
  3146. if event.key == 'R':
  3147. self.on_rotate(silent=True, preset=90)
  3148. if event.key == 'S':
  3149. self.on_toggle_shell()
  3150. if event.key == 'V':
  3151. self.on_zoom_fit(None)
  3152. if event.key == 'X':
  3153. self.on_flipx()
  3154. if event.key == 'Y':
  3155. self.on_flipy()
  3156. if event.key == '`':
  3157. self.on_shortcut_list()
  3158. def on_key_release_over_plot(self, event):
  3159. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3160. if modifiers == QtCore.Qt.ControlModifier:
  3161. return
  3162. elif modifiers == QtCore.Qt.AltModifier:
  3163. # place holder for further shortcut key
  3164. return
  3165. elif modifiers == QtCore.Qt.ShiftModifier:
  3166. # place holder for further shortcut key
  3167. return
  3168. else:
  3169. return
  3170. def on_shortcut_list(self):
  3171. msg = '''<b>Shortcut list</b><br>
  3172. <br>
  3173. <b>~:</b> Show Shortcut List<br>
  3174. <br>
  3175. <b>1:</b> Zoom Fit<br>
  3176. <b>2:</b> Zoom Out<br>
  3177. <b>3:</b> Zoom In<br>
  3178. <b>A:</b> Draw an Arc (when in Edit Mode)<br>
  3179. <b>C:</b> Copy Geo Item (when in Edit Mode)<br>
  3180. <b>E:</b> Edit Object (if selected)<br>
  3181. <b>G:</b> Grid On/Off<br>
  3182. <b>J:</b> Jump to Coordinates<br>
  3183. <b>L:</b> New Excellon<br>
  3184. <b>M:</b> Move Obj<br>
  3185. <b>M:</b> Move Geo Item (when in Edit Mode)<br>
  3186. <b>N:</b> New Geometry<br>
  3187. <b>N:</b> Draw a Polygon (when in Edit Mode)<br>
  3188. <b>O:</b> Set Origin<br>
  3189. <b>O:</b> Draw a Circle (when in Edit Mode)<br>
  3190. <b>Q:</b> Change Units<br>
  3191. <b>P:</b> Open Properties Tool<br>
  3192. <b>P:</b> Draw a Path (when in Edit Mode)<br>
  3193. <b>R:</b> Rotate by 90 degree CW<br>
  3194. <b>R:</b> Draw Rectangle (when in Edit Mode)<br>
  3195. <b>S:</b> Shell Toggle<br>
  3196. <b>V:</b> View Fit<br>
  3197. <b>X:</b> Flip on X_axis<br>
  3198. <b>Y:</b> Flip on Y_axis<br>
  3199. <br>
  3200. <b>Space:</b> En(Dis)able Obj Plot<br>
  3201. <b>CTRL+A:</b> Select All<br>
  3202. <b>CTRL+C:</b> Copy Obj<br>
  3203. <b>CTRL+E:</b> Open Excellon File<br>
  3204. <b>CTRL+G:</b> Open Gerber File<br>
  3205. <b>CTRL+N:</b> New Project<br>
  3206. <b>CTRL+M:</b> Measurement Tool<br>
  3207. <b>CTRL+O:</b> Open Project<br>
  3208. <b>CTRL+S:</b> Save Project As<br>
  3209. <b>CTRL+S:</b> Save Object and Exit Editor (when in Edit Mode)<br>
  3210. <br>
  3211. <b>SHIFT+C:</b> Copy Obj_Name<br>
  3212. <b>SHIFT+G:</b> Toggle the axis<br>
  3213. <b>SHIFT+P:</b> Open Preferences Window<br>
  3214. <b>SHIFT+R:</b> Rotate by 90 degree CCW<br>
  3215. <b>SHIFT+S:</b> Run a Script<br>
  3216. <b>SHIFT+W:</b> Toggle the workspace<br>
  3217. <b>SHIFT+X:</b> Skew on X axis<br>
  3218. <b>SHIFT+Y:</b> Skew on Y axis<br>
  3219. <br>
  3220. <b>ALT+C:</b> Calculators Tool<br>
  3221. <b>ALT+D:</b> 2-Sided PCB Tool<br>
  3222. <b>ALT+L:</b> Film PCB Tool<br>
  3223. <b>ALT+N:</b> Non-Copper Clearing Tool<br>
  3224. <b>ALT+P:</b> Paint Area Tool<br>
  3225. <b>ALT+R:</b> Transformation Tool<br>
  3226. <b>ALT+U:</b> Cutout PCB Tool<br>
  3227. <br>
  3228. <b>F1:</b> Open Online Manual<br>
  3229. <b>F2:</b> Open Online Tutorials<br>
  3230. <b>Del:</b> Delete Obj
  3231. '''
  3232. helpbox = QtWidgets.QMessageBox()
  3233. helpbox.setText(msg)
  3234. helpbox.setWindowTitle("Help")
  3235. helpbox.setWindowIcon(QtGui.QIcon('share/help.png'))
  3236. helpbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3237. helpbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3238. helpbox.exec_()
  3239. def on_copy_name(self):
  3240. obj = self.collection.get_active()
  3241. try:
  3242. name = obj.options["name"]
  3243. except AttributeError:
  3244. log.debug("on_copy_name() --> No object selected to copy it's name")
  3245. self.inform.emit("[warning_notcl]No object selected to copy it's name")
  3246. return
  3247. self.clipboard.setText(name)
  3248. self.inform.emit("Name copied on clipboard ...")
  3249. def on_mouse_click_over_plot(self, event):
  3250. """
  3251. Callback for the mouse click event over the plot. This event is generated
  3252. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3253. For details, see: http://matplotlib.org/users/event_handling.html
  3254. Default actions are:
  3255. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3256. :param event: Contains information about the event, like which button
  3257. was clicked, the pixel coordinates and the axes coordinates.
  3258. :return: None
  3259. """
  3260. self.pos = []
  3261. # So it can receive key presses
  3262. self.plotcanvas.vispy_canvas.native.setFocus()
  3263. # Set the mouse button for panning
  3264. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3265. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3266. if self.grid_status() == True:
  3267. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3268. self.app_cursor.enabled = True
  3269. else:
  3270. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3271. self.app_cursor.enabled = False
  3272. try:
  3273. App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3274. event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3275. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3276. if event.button == 1:
  3277. # Reset here the relative coordinates so there is a new reference on the click position
  3278. if self.rel_point1 is None:
  3279. self.rel_point1 = self.pos
  3280. else:
  3281. self.rel_point2 = copy(self.rel_point1)
  3282. self.rel_point1 = self.pos
  3283. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3284. if modifiers == QtCore.Qt.ShiftModifier:
  3285. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3286. return
  3287. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3288. # and if it's not selected then it will be selected
  3289. if modifiers == QtCore.Qt.ControlModifier:
  3290. # If there is no active command (self.command_active is None) then we check if we clicked on
  3291. # a object by checking the bounding limits against mouse click position
  3292. if self.command_active is None:
  3293. self.select_objects(key='CTRL')
  3294. else:
  3295. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3296. # checking the bounding limits against mouse click position
  3297. if self.command_active is None:
  3298. self.select_objects()
  3299. self.on_mouse_move_over_plot(event, origin_click=True)
  3300. except Exception as e:
  3301. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3302. def on_double_click_over_plot(self, event):
  3303. # make double click work only for the LMB
  3304. if event.button == 1:
  3305. if not self.collection.get_selected():
  3306. pass
  3307. else:
  3308. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3309. #delete the selection shape(S) as it may be in the way
  3310. self.delete_selection_shape()
  3311. def on_mouse_move_over_plot(self, event, origin_click=None):
  3312. """
  3313. Callback for the mouse motion event over the plot. This event is generated
  3314. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3315. For details, see: http://matplotlib.org/users/event_handling.html
  3316. :param event: Contains information about the event.
  3317. :param origin_click
  3318. :return: None
  3319. """
  3320. # So it can receive key presses
  3321. self.plotcanvas.vispy_canvas.native.setFocus()
  3322. self.pos_jump = event.pos
  3323. if origin_click is True:
  3324. pass
  3325. else:
  3326. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3327. if event.button == 2:
  3328. self.panning_action = True
  3329. return
  3330. else:
  3331. self.panning_action = False
  3332. if self.rel_point1 is not None:
  3333. try: # May fail in case mouse not within axes
  3334. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3335. if self.grid_status():
  3336. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3337. self.app_cursor.enabled = True
  3338. # Update cursor
  3339. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3340. else:
  3341. pos = (pos_canvas[0], pos_canvas[1])
  3342. self.app_cursor.enabled = False
  3343. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3344. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3345. dx = pos[0] - self.rel_point1[0]
  3346. dy = pos[1] - self.rel_point1[1]
  3347. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3348. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3349. self.mouse = [pos[0], pos[1]]
  3350. # if the mouse is moved and the LMB is clicked then the action is a selection
  3351. if event.is_dragging == 1 and event.button == 1:
  3352. self.delete_selection_shape()
  3353. if dx < 0:
  3354. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3355. face_color=self.defaults['global_alt_sel_fill'])
  3356. self.selection_type = False
  3357. else:
  3358. self.draw_moving_selection_shape(self.pos, pos)
  3359. self.selection_type = True
  3360. # delete the status message on mouse move
  3361. # self.inform.emit("")
  3362. except:
  3363. self.ui.position_label.setText("")
  3364. self.ui.rel_position_label.setText("")
  3365. self.mouse = None
  3366. def on_mouse_click_release_over_plot(self, event):
  3367. """
  3368. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3369. and has been registered in ''self.__init__()''.
  3370. :param event: contains information about the event.
  3371. :return:
  3372. """
  3373. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3374. if self.grid_status():
  3375. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3376. else:
  3377. pos = (pos_canvas[0], pos_canvas[1])
  3378. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3379. # canvas menu
  3380. try:
  3381. if event.button == 2: # right click
  3382. if self.panning_action is True:
  3383. self.panning_action = False
  3384. else:
  3385. self.cursor = QtGui.QCursor()
  3386. self.ui.popMenu.popup(self.cursor.pos())
  3387. except Exception as e:
  3388. log.warning("Error: %s" % str(e))
  3389. return
  3390. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3391. # selection and then select a type of selection ("enclosing" or "touching")
  3392. try:
  3393. if event.button == 1: # left click
  3394. if self.selection_type is not None:
  3395. self.selection_area_handler(self.pos, pos, self.selection_type)
  3396. self.selection_type = None
  3397. except Exception as e:
  3398. log.warning("Error: %s" % str(e))
  3399. return
  3400. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3401. """
  3402. :param start_pos: mouse position when the selection LMB click was done
  3403. :param end_pos: mouse position when the left mouse button is released
  3404. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3405. :return:
  3406. """
  3407. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3408. self.delete_selection_shape()
  3409. for obj in self.collection.get_list():
  3410. try:
  3411. # select the object(s) only if it is enabled (plotted)
  3412. if obj.options['plot']:
  3413. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3414. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3415. if sel_type is True:
  3416. if poly_obj.within(poly_selection):
  3417. # create the selection box around the selected object
  3418. self.draw_selection_shape(obj)
  3419. self.collection.set_active(obj.options['name'])
  3420. else:
  3421. if poly_selection.intersects(poly_obj):
  3422. # create the selection box around the selected object
  3423. self.draw_selection_shape(obj)
  3424. self.collection.set_active(obj.options['name'])
  3425. except:
  3426. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3427. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3428. # In this case poly_obj creation (see above) will fail
  3429. pass
  3430. def select_objects(self, key=None):
  3431. # list where we store the overlapped objects under our mouse left click position
  3432. objects_under_the_click_list = []
  3433. # Populate the list with the overlapped objects on the click position
  3434. curr_x, curr_y = self.pos
  3435. for obj in self.all_objects_list:
  3436. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3437. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3438. if obj.options['name'] not in objects_under_the_click_list:
  3439. if obj.options['plot']:
  3440. # add objects to the objects_under_the_click list only if the object is plotted
  3441. # (active and not disabled)
  3442. objects_under_the_click_list.append(obj.options['name'])
  3443. try:
  3444. # If there is no element in the overlapped objects list then make everyone inactive
  3445. # because we selected "nothing"
  3446. if not objects_under_the_click_list:
  3447. self.collection.set_all_inactive()
  3448. # delete the possible selection box around a possible selected object
  3449. self.delete_selection_shape()
  3450. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3451. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3452. else:
  3453. # case when there is only an object under the click and we toggle it
  3454. if len(objects_under_the_click_list) == 1:
  3455. if self.collection.get_active() is None :
  3456. self.collection.set_active(objects_under_the_click_list[0])
  3457. # create the selection box around the selected object
  3458. curr_sel_obj = self.collection.get_active()
  3459. self.draw_selection_shape(curr_sel_obj)
  3460. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3461. self.collection.set_all_inactive()
  3462. self.delete_selection_shape()
  3463. self.collection.set_active(objects_under_the_click_list[0])
  3464. # create the selection box around the selected object
  3465. curr_sel_obj = self.collection.get_active()
  3466. self.draw_selection_shape(curr_sel_obj)
  3467. else:
  3468. self.collection.set_all_inactive()
  3469. self.delete_selection_shape()
  3470. else:
  3471. # If there is no selected object
  3472. # make active the first element of the overlapped objects list
  3473. if self.collection.get_active() is None:
  3474. self.collection.set_active(objects_under_the_click_list[0])
  3475. name_sel_obj = self.collection.get_active().options['name']
  3476. # In case that there is a selected object but it is not in the overlapped object list
  3477. # make that object inactive and activate the first element in the overlapped object list
  3478. if name_sel_obj not in objects_under_the_click_list:
  3479. self.collection.set_inactive(name_sel_obj)
  3480. name_sel_obj = objects_under_the_click_list[0]
  3481. self.collection.set_active(name_sel_obj)
  3482. else:
  3483. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3484. self.collection.set_all_inactive()
  3485. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) % len(objects_under_the_click_list)])
  3486. curr_sel_obj = self.collection.get_active()
  3487. # delete the possible selection box around a possible selected object
  3488. self.delete_selection_shape()
  3489. # create the selection box around the selected object
  3490. self.draw_selection_shape(curr_sel_obj)
  3491. # for obj in self.collection.get_list():
  3492. # obj.plot()
  3493. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3494. # TODO: on selected objects change the object colors and do not draw the selection box
  3495. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3496. except Exception as e:
  3497. log.error("[error] Something went bad. %s" % str(e))
  3498. return
  3499. def delete_selection_shape(self):
  3500. self.move_tool.sel_shapes.clear()
  3501. self.move_tool.sel_shapes.redraw()
  3502. def draw_selection_shape(self, sel_obj):
  3503. """
  3504. :param sel_obj: the object for which the selection shape must be drawn
  3505. :return:
  3506. """
  3507. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3508. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3509. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3510. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3511. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3512. #blue_t = Color('blue')
  3513. blue_t = Color(self.defaults['global_sel_fill'])
  3514. blue_t.alpha = 0.3
  3515. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3516. face_color=blue_t, update=True, layer=0, tolerance=None))
  3517. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3518. """
  3519. :param old_coords: old coordinates
  3520. :param coords: new coordinates
  3521. :return:
  3522. """
  3523. if 'color' in kwargs:
  3524. color = kwargs['color']
  3525. else:
  3526. color = self.defaults['global_sel_line']
  3527. if 'face_color' in kwargs:
  3528. face_color = kwargs['face_color']
  3529. else:
  3530. face_color = self.defaults['global_sel_fill']
  3531. x0, y0 = old_coords
  3532. x1, y1 = coords
  3533. pt1 = (x0, y0)
  3534. pt2 = (x1, y0)
  3535. pt3 = (x1, y1)
  3536. pt4 = (x0, y1)
  3537. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3538. color_t = Color(face_color)
  3539. color_t.alpha = 0.3
  3540. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  3541. layer=0, tolerance=None)
  3542. def on_file_new_click(self):
  3543. if self.collection.get_list():
  3544. msgbox = QtWidgets.QMessageBox()
  3545. # msgbox.setText("<B>Save changes ...</B>")
  3546. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  3547. "Creating a New project will delete them.\n"
  3548. "Do you want to Save the project?")
  3549. msgbox.setWindowTitle("Save changes")
  3550. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3551. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  3552. QtWidgets.QMessageBox.No)
  3553. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3554. response = msgbox.exec_()
  3555. if response == QtWidgets.QMessageBox.Yes:
  3556. self.on_file_saveprojectas()
  3557. elif response == QtWidgets.QMessageBox.Cancel:
  3558. return
  3559. self.on_file_new()
  3560. else:
  3561. self.on_file_new()
  3562. self.inform.emit("[success] New Project created...")
  3563. def on_file_new(self):
  3564. """
  3565. Callback for menu item File->New. Returns the application to its
  3566. startup state. This method is thread-safe.
  3567. :return: None
  3568. """
  3569. self.report_usage("on_file_new")
  3570. # Remove everything from memory
  3571. App.log.debug("on_file_new()")
  3572. # Clear pool
  3573. self.clear_pool()
  3574. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  3575. self.init_tcl()
  3576. self.delete_selection_shape()
  3577. self.collection.delete_all()
  3578. self.setup_component_editor()
  3579. # Clear project filename
  3580. self.project_filename = None
  3581. # Load the application defaults
  3582. self.load_defaults(filename='current_defaults')
  3583. # Re-fresh project options
  3584. self.on_options_app2project()
  3585. # Init Tools
  3586. self.init_tools()
  3587. # take the focus of the Notebook on Project Tab.
  3588. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3589. def obj_properties(self):
  3590. self.properties_tool.run()
  3591. def obj_move(self):
  3592. self.move_tool.run()
  3593. def on_fileopengerber(self):
  3594. """
  3595. File menu callback for opening a Gerber.
  3596. :return: None
  3597. """
  3598. self.report_usage("on_fileopengerber")
  3599. App.log.debug("on_fileopengerber()")
  3600. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3601. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3602. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3603. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3604. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3605. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3606. "Allegro Files (*.art);;" \
  3607. "Mentor Files (*.pho *.gdo);;" \
  3608. "All Files (*.*)"
  3609. try:
  3610. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  3611. directory=self.get_last_folder(), filter=_filter_)
  3612. except TypeError:
  3613. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  3614. filenames = [str(filename) for filename in filenames]
  3615. if len(filenames) == 0:
  3616. self.inform.emit("[warning_notcl]Open Gerber cancelled.")
  3617. else:
  3618. for filename in filenames:
  3619. if filename != '':
  3620. self.worker_task.emit({'fcn': self.open_gerber,
  3621. 'params': [filename]})
  3622. def on_fileopengerber_follow(self):
  3623. """
  3624. File menu callback for opening a Gerber.
  3625. :return: None
  3626. """
  3627. self.report_usage("on_fileopengerber_follow")
  3628. App.log.debug("on_fileopengerber_follow()")
  3629. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  3630. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  3631. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  3632. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  3633. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  3634. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  3635. "Allegro Files (*.art);;" \
  3636. "Mentor Files (*.pho *.gdo);;" \
  3637. "All Files (*.*)"
  3638. try:
  3639. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow",
  3640. directory=self.get_last_folder(), filter=_filter_)
  3641. except TypeError:
  3642. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Gerber with Follow", filter=_filter_)
  3643. # The Qt methods above will return a QString which can cause problems later.
  3644. # So far json.dump() will fail to serialize it.
  3645. # TODO: Improve the serialization methods and remove this fix.
  3646. filename = str(filename)
  3647. follow = True
  3648. if filename == "":
  3649. self.inform.emit("[warning_notcl]Open Gerber-Follow cancelled.")
  3650. else:
  3651. self.worker_task.emit({'fcn': self.open_gerber,
  3652. 'params': [filename, follow]})
  3653. def on_fileopenexcellon(self):
  3654. """
  3655. File menu callback for opening an Excellon file.
  3656. :return: None
  3657. """
  3658. self.report_usage("on_fileopenexcellon")
  3659. App.log.debug("on_fileopenexcellon()")
  3660. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  3661. "All Files (*.*)"
  3662. try:
  3663. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  3664. directory=self.get_last_folder(), filter=_filter_)
  3665. except TypeError:
  3666. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  3667. filenames = [str(filename) for filename in filenames]
  3668. if len(filenames) == 0:
  3669. self.inform.emit("[warning_notcl]Open Excellon cancelled.")
  3670. else:
  3671. for filename in filenames:
  3672. if filename != '':
  3673. self.worker_task.emit({'fcn': self.open_excellon,
  3674. 'params': [filename]})
  3675. def on_fileopengcode(self):
  3676. """
  3677. File menu call back for opening gcode.
  3678. :return: None
  3679. """
  3680. self.report_usage("on_fileopengcode")
  3681. App.log.debug("on_fileopengcode()")
  3682. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  3683. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  3684. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  3685. "All Files (*.*)"
  3686. try:
  3687. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  3688. directory=self.get_last_folder(), filter=_filter_)
  3689. except TypeError:
  3690. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  3691. filenames = [str(filename) for filename in filenames]
  3692. if len(filenames) == 0:
  3693. self.inform.emit("[warning_notcl]Open G-Code cancelled.")
  3694. else:
  3695. for filename in filenames:
  3696. if filename != '':
  3697. self.worker_task.emit({'fcn': self.open_gcode,
  3698. 'params': [filename]})
  3699. def on_file_openproject(self):
  3700. """
  3701. File menu callback for opening a project.
  3702. :return: None
  3703. """
  3704. self.report_usage("on_file_openproject")
  3705. App.log.debug("on_file_openproject()")
  3706. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  3707. try:
  3708. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  3709. directory=self.get_last_folder(), filter=_filter_)
  3710. except TypeError:
  3711. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  3712. # The Qt methods above will return a QString which can cause problems later.
  3713. # So far json.dump() will fail to serialize it.
  3714. # TODO: Improve the serialization methods and remove this fix.
  3715. filename = str(filename)
  3716. if filename == "":
  3717. self.inform.emit("[warning_notcl]Open Project cancelled.")
  3718. else:
  3719. # self.worker_task.emit({'fcn': self.open_project,
  3720. # 'params': [filename]})
  3721. # The above was failing because open_project() is not
  3722. # thread safe. The new_project()
  3723. self.open_project(filename)
  3724. def on_file_exportsvg(self):
  3725. """
  3726. Callback for menu item File->Export SVG.
  3727. :return: None
  3728. """
  3729. self.report_usage("on_file_exportsvg")
  3730. App.log.debug("on_file_exportsvg()")
  3731. obj = self.collection.get_active()
  3732. if obj is None:
  3733. self.inform.emit("WARNING: No object selected.")
  3734. msg = "Please Select a Geometry object to export"
  3735. msgbox = QtWidgets.QMessageBox()
  3736. msgbox.setInformativeText(msg)
  3737. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3738. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3739. msgbox.exec_()
  3740. return
  3741. # Check for more compatible types and add as required
  3742. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  3743. and not isinstance(obj, FlatCAMExcellon)):
  3744. msg = "[error_notcl] Only Geometry, Gerber and CNCJob objects can be used."
  3745. msgbox = QtWidgets.QMessageBox()
  3746. msgbox.setInformativeText(msg)
  3747. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3748. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3749. msgbox.exec_()
  3750. return
  3751. name = self.collection.get_active().options["name"]
  3752. filter = "SVG File (*.svg);;All Files (*.*)"
  3753. try:
  3754. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG",
  3755. directory=self.get_last_save_folder(), filter=filter)
  3756. except TypeError:
  3757. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  3758. filename = str(filename)
  3759. if filename == "":
  3760. self.inform.emit("[warning_notcl]Export SVG cancelled.")
  3761. return
  3762. else:
  3763. self.export_svg(name, filename)
  3764. self.file_saved.emit("SVG", filename)
  3765. def on_file_exportpng(self):
  3766. self.report_usage("on_file_exportpng")
  3767. App.log.debug("on_file_exportpng()")
  3768. image = _screenshot()
  3769. data = np.asarray(image)
  3770. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  3771. self.inform.emit('[[warning_notcl]] Data must be a 3D array with last dimension 3 or 4')
  3772. return
  3773. filter = "PNG File (*.png);;All Files (*.*)"
  3774. try:
  3775. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image",
  3776. directory=self.get_last_save_folder(), filter=filter)
  3777. except TypeError:
  3778. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter)
  3779. filename = str(filename)
  3780. if filename == "":
  3781. self.inform.emit("Export PNG cancelled.")
  3782. return
  3783. else:
  3784. write_png(filename, data)
  3785. self.file_saved.emit("png", filename)
  3786. def on_file_exportexcellon(self, altium_format=None):
  3787. """
  3788. Callback for menu item File->Export SVG.
  3789. :return: None
  3790. """
  3791. self.report_usage("on_file_exportexcellon")
  3792. App.log.debug("on_file_exportexcellon()")
  3793. obj = self.collection.get_active()
  3794. if obj is None:
  3795. self.inform.emit("[warning_notcl] No object selected.")
  3796. msg = "Please Select an Excellon object to export"
  3797. msgbox = QtWidgets.QMessageBox()
  3798. msgbox.setInformativeText(msg)
  3799. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3800. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3801. msgbox.exec_()
  3802. return
  3803. # Check for more compatible types and add as required
  3804. if not isinstance(obj, FlatCAMExcellon):
  3805. msg = "[warning_notcl] Only Excellon objects can be used."
  3806. msgbox = QtWidgets.QMessageBox()
  3807. msgbox.setInformativeText(msg)
  3808. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3809. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3810. msgbox.exec_()
  3811. return
  3812. name = self.collection.get_active().options["name"]
  3813. filter = "Excellon File (*.drl);;Excellon File (*.txt);;All Files (*.*)"
  3814. try:
  3815. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon",
  3816. directory=self.get_last_save_folder(), filter=filter)
  3817. except TypeError:
  3818. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  3819. filename = str(filename)
  3820. if filename == "":
  3821. self.inform.emit("[warning_notcl]Export Excellon cancelled.")
  3822. return
  3823. else:
  3824. if altium_format == None:
  3825. self.export_excellon(name, filename)
  3826. self.file_saved.emit("Excellon", filename)
  3827. else:
  3828. self.export_excellon(name, filename, altium_format=True)
  3829. self.file_saved.emit("Excellon", filename)
  3830. def on_file_exportdxf(self):
  3831. """
  3832. Callback for menu item File->Export DXF.
  3833. :return: None
  3834. """
  3835. self.report_usage("on_file_exportdxf")
  3836. App.log.debug("on_file_exportdxf()")
  3837. obj = self.collection.get_active()
  3838. if obj is None:
  3839. self.inform.emit("W[warning_notcl] No object selected.")
  3840. msg = "Please Select a Geometry object to export"
  3841. msgbox = QtWidgets.QMessageBox()
  3842. msgbox.setInformativeText(msg)
  3843. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3844. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3845. msgbox.exec_()
  3846. return
  3847. # Check for more compatible types and add as required
  3848. if not isinstance(obj, FlatCAMGeometry):
  3849. msg = "[error_notcl] Only Geometry objects can be used."
  3850. msgbox = QtWidgets.QMessageBox()
  3851. msgbox.setInformativeText(msg)
  3852. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3853. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3854. msgbox.exec_()
  3855. return
  3856. name = self.collection.get_active().options["name"]
  3857. filter = "DXF File (*.DXF);;All Files (*.*)"
  3858. try:
  3859. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF",
  3860. directory=self.get_last_save_folder(), filter=filter)
  3861. except TypeError:
  3862. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  3863. filename = str(filename)
  3864. if filename == "":
  3865. self.inform.emit("[warning_notcl]Export DXF cancelled.")
  3866. return
  3867. else:
  3868. self.export_dxf(name, filename)
  3869. self.file_saved.emit("DXF", filename)
  3870. def on_file_importsvg(self, type_of_obj):
  3871. """
  3872. Callback for menu item File->Import SVG.
  3873. :param type_of_obj: to import the SVG as Geometry or as Gerber
  3874. :type type_of_obj: str
  3875. :return: None
  3876. """
  3877. self.report_usage("on_file_importsvg")
  3878. App.log.debug("on_file_importsvg()")
  3879. filter = "SVG File (*.svg);;All Files (*.*)"
  3880. try:
  3881. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  3882. directory=self.get_last_folder(), filter=filter)
  3883. except TypeError:
  3884. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  3885. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3886. type_of_obj = "geometry"
  3887. filenames = [str(filename) for filename in filenames]
  3888. if len(filenames) == 0:
  3889. self.inform.emit("[warning_notcl]Open SVG cancelled.")
  3890. else:
  3891. for filename in filenames:
  3892. if filename != '':
  3893. self.worker_task.emit({'fcn': self.import_svg,
  3894. 'params': [filename, type_of_obj]})
  3895. def on_file_importdxf(self, type_of_obj):
  3896. """
  3897. Callback for menu item File->Import DXF.
  3898. :param type_of_obj: to import the DXF as Geometry or as Gerber
  3899. :type type_of_obj: str
  3900. :return: None
  3901. """
  3902. self.report_usage("on_file_importdxf")
  3903. App.log.debug("on_file_importdxf()")
  3904. filter = "DXF File (*.DXF);;All Files (*.*)"
  3905. try:
  3906. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  3907. directory=self.get_last_folder(), filter=filter)
  3908. except TypeError:
  3909. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  3910. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  3911. type_of_obj = "geometry"
  3912. filenames = [str(filename) for filename in filenames]
  3913. if len(filenames) == 0:
  3914. self.inform.emit("[warning_notcl]Open DXF cancelled.")
  3915. else:
  3916. for filename in filenames:
  3917. if filename != '':
  3918. self.worker_task.emit({'fcn': self.import_dxf,
  3919. 'params': [filename, type_of_obj]})
  3920. def on_filerunscript(self):
  3921. """
  3922. File menu callback for loading and running a TCL script.
  3923. :return: None
  3924. """
  3925. self.report_usage("on_filerunscript")
  3926. App.log.debug("on_file_runscript()")
  3927. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  3928. try:
  3929. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  3930. directory=self.get_last_folder(), filter=_filter_)
  3931. except TypeError:
  3932. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  3933. # The Qt methods above will return a QString which can cause problems later.
  3934. # So far json.dump() will fail to serialize it.
  3935. # TODO: Improve the serialization methods and remove this fix.
  3936. filename = str(filename)
  3937. if filename == "":
  3938. self.inform.emit("[warning_notcl]Open TCL script cancelled.")
  3939. else:
  3940. try:
  3941. with open(filename, "r") as tcl_script:
  3942. cmd_line_shellfile_content = tcl_script.read()
  3943. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  3944. except Exception as ext:
  3945. print("ERROR: ", ext)
  3946. sys.exit(2)
  3947. def on_file_saveproject(self):
  3948. """
  3949. Callback for menu item File->Save Project. Saves the project to
  3950. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  3951. if set to None. The project is saved by calling ``self.save_project()``.
  3952. :return: None
  3953. """
  3954. self.report_usage("on_file_saveproject")
  3955. if self.project_filename is None:
  3956. self.on_file_saveprojectas()
  3957. else:
  3958. self.worker_task.emit({'fcn': self.save_project,
  3959. 'params': [self.project_filename]})
  3960. # self.save_project(self.project_filename)
  3961. self.file_opened.emit("project", self.project_filename)
  3962. self.file_saved.emit("project", self.project_filename)
  3963. def on_file_saveprojectas(self, make_copy=False, thread=True):
  3964. """
  3965. Callback for menu item File->Save Project As... Opens a file
  3966. chooser and saves the project to the given file via
  3967. ``self.save_project()``.
  3968. :return: None
  3969. """
  3970. self.report_usage("on_file_saveprojectas")
  3971. filter = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  3972. try:
  3973. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...",
  3974. directory=self.get_last_save_folder(), filter=filter)
  3975. except TypeError:
  3976. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter)
  3977. filename = str(filename)
  3978. if filename == '':
  3979. self.inform.emit("[warning_notcl]Save Project cancelled.")
  3980. return
  3981. try:
  3982. f = open(filename, 'r')
  3983. f.close()
  3984. exists = True
  3985. except IOError:
  3986. exists = False
  3987. msg = "File exists. Overwrite?"
  3988. if exists:
  3989. msgbox = QtWidgets.QMessageBox()
  3990. msgbox.setInformativeText(msg)
  3991. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  3992. msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  3993. result = msgbox.exec_()
  3994. if result ==QtWidgets.QMessageBox.Cancel:
  3995. return
  3996. if thread is True:
  3997. self.worker_task.emit({'fcn': self.save_project,
  3998. 'params': [filename]})
  3999. else:
  4000. self.save_project(filename)
  4001. # self.save_project(filename)
  4002. self.file_opened.emit("project", filename)
  4003. self.file_saved.emit("project", filename)
  4004. if not make_copy:
  4005. self.project_filename = filename
  4006. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4007. """
  4008. Exports a Geometry Object to an SVG file.
  4009. :param filename: Path to the SVG file to save to.
  4010. :return:
  4011. """
  4012. if filename is None:
  4013. filename = self.defaults["global_last_save_folder"]
  4014. self.log.debug("export_svg()")
  4015. try:
  4016. obj = self.collection.get_by_name(str(obj_name))
  4017. except:
  4018. # TODO: The return behavior has not been established... should raise exception?
  4019. return "Could not retrieve object: %s" % obj_name
  4020. with self.proc_container.new("Exporting SVG") as proc:
  4021. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4022. # Determine bounding area for svg export
  4023. bounds = obj.bounds()
  4024. size = obj.size()
  4025. # Convert everything to strings for use in the xml doc
  4026. svgwidth = str(size[0])
  4027. svgheight = str(size[1])
  4028. minx = str(bounds[0])
  4029. miny = str(bounds[1] - size[1])
  4030. uom = obj.units.lower()
  4031. # Add a SVG Header and footer to the svg output from shapely
  4032. # The transform flips the Y Axis so that everything renders
  4033. # properly within svg apps such as inkscape
  4034. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4035. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4036. svg_header += 'width="' + svgwidth + uom + '" '
  4037. svg_header += 'height="' + svgheight + uom + '" '
  4038. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4039. svg_header += '<g transform="scale(1,-1)">'
  4040. svg_footer = '</g> </svg>'
  4041. svg_elem = svg_header + exported_svg + svg_footer
  4042. # Parse the xml through a xml parser just to add line feeds
  4043. # and to make it look more pretty for the output
  4044. svgcode = parse_xml_string(svg_elem)
  4045. with open(filename, 'w') as fp:
  4046. fp.write(svgcode.toprettyxml())
  4047. self.file_saved.emit("SVG", filename)
  4048. self.inform.emit("[success] SVG file exported to " + filename)
  4049. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4050. """
  4051. Exports a Geometry Object to an SVG file in negative.
  4052. :param filename: Path to the SVG file to save to.
  4053. :param: use_thread: If True use threads
  4054. :type: Bool
  4055. :return:
  4056. """
  4057. if filename is None:
  4058. filename = self.defaults["global_last_save_folder"]
  4059. self.log.debug("export_svg() negative")
  4060. try:
  4061. obj = self.collection.get_by_name(str(obj_name))
  4062. except:
  4063. # TODO: The return behavior has not been established... should raise exception?
  4064. return "Could not retrieve object: %s" % obj_name
  4065. try:
  4066. box = self.collection.get_by_name(str(box_name))
  4067. except:
  4068. # TODO: The return behavior has not been established... should raise exception?
  4069. return "Could not retrieve object: %s" % box_name
  4070. if box is None:
  4071. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4072. box = obj
  4073. def make_negative_film():
  4074. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4075. self.progress.emit(40)
  4076. # Determine bounding area for svg export
  4077. bounds = box.bounds()
  4078. size = box.size()
  4079. uom = obj.units.lower()
  4080. # Convert everything to strings for use in the xml doc
  4081. svgwidth = str(size[0] + (2 * boundary))
  4082. svgheight = str(size[1] + (2 * boundary))
  4083. minx = str(bounds[0] - boundary)
  4084. miny = str(bounds[1] + boundary + size[1])
  4085. miny_rect = str(bounds[1] - boundary)
  4086. # Add a SVG Header and footer to the svg output from shapely
  4087. # The transform flips the Y Axis so that everything renders
  4088. # properly within svg apps such as inkscape
  4089. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4090. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4091. svg_header += 'width="' + svgwidth + uom + '" '
  4092. svg_header += 'height="' + svgheight + uom + '" '
  4093. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4094. svg_header += '>'
  4095. svg_header += '<g transform="scale(1,-1)">'
  4096. svg_footer = '</g> </svg>'
  4097. self.progress.emit(60)
  4098. # Change the attributes of the exported SVG
  4099. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4100. # We set opacity to maximum
  4101. # We set the color to WHITE
  4102. root = ET.fromstring(exported_svg)
  4103. for child in root:
  4104. child.set('fill', '#FFFFFF')
  4105. child.set('opacity', '1.0')
  4106. child.set('stroke', '#FFFFFF')
  4107. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4108. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4109. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4110. first_svg_elem_tag = 'rect'
  4111. first_svg_elem_attribs = {
  4112. 'x': minx,
  4113. 'y': miny_rect,
  4114. 'width': svgwidth,
  4115. 'height': svgheight,
  4116. 'id': 'neg_rect',
  4117. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4118. }
  4119. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4120. exported_svg = ET.tostring(root)
  4121. svg_elem = svg_header + str(exported_svg) + svg_footer
  4122. self.progress.emit(80)
  4123. # Parse the xml through a xml parser just to add line feeds
  4124. # and to make it look more pretty for the output
  4125. doc = parse_xml_string(svg_elem)
  4126. with open(filename, 'w') as fp:
  4127. fp.write(doc.toprettyxml())
  4128. self.progress.emit(100)
  4129. self.file_saved.emit("SVG", filename)
  4130. self.inform.emit("[success] SVG file exported to " + filename)
  4131. if use_thread is True:
  4132. proc = self.proc_container.new("Generating Film ... Please wait.")
  4133. def job_thread_film(app_obj):
  4134. try:
  4135. make_negative_film()
  4136. except Exception as e:
  4137. proc.done()
  4138. return
  4139. proc.done()
  4140. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4141. else:
  4142. make_negative_film()
  4143. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4144. """
  4145. Exports a Geometry Object to an SVG file in negative.
  4146. :param filename: Path to the SVG file to save to.
  4147. :param: use_thread: If True use threads
  4148. :type: Bool
  4149. :return:
  4150. """
  4151. if filename is None:
  4152. filename = self.defaults["global_last_save_folder"]
  4153. self.log.debug("export_svg() black")
  4154. try:
  4155. obj = self.collection.get_by_name(str(obj_name))
  4156. except:
  4157. # TODO: The return behavior has not been established... should raise exception?
  4158. return "Could not retrieve object: %s" % obj_name
  4159. try:
  4160. box = self.collection.get_by_name(str(box_name))
  4161. except:
  4162. # TODO: The return behavior has not been established... should raise exception?
  4163. return "Could not retrieve object: %s" % box_name
  4164. if box is None:
  4165. self.inform.emit("[warning_notcl]No object Box. Using instead %s" % obj)
  4166. box = obj
  4167. def make_black_film():
  4168. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4169. self.progress.emit(40)
  4170. # Change the attributes of the exported SVG
  4171. # We don't need stroke-width
  4172. # We set opacity to maximum
  4173. # We set the colour to WHITE
  4174. root = ET.fromstring(exported_svg)
  4175. for child in root:
  4176. child.set('fill', '#000000')
  4177. child.set('opacity', '1.0')
  4178. child.set('stroke', '#000000')
  4179. exported_svg = ET.tostring(root)
  4180. # Determine bounding area for svg export
  4181. bounds = box.bounds()
  4182. size = box.size()
  4183. # This contain the measure units
  4184. uom = obj.units.lower()
  4185. # Define a boundary around SVG of about 1.0mm (~39mils)
  4186. if uom in "mm":
  4187. boundary = 1.0
  4188. else:
  4189. boundary = 0.0393701
  4190. self.progress.emit(80)
  4191. # Convert everything to strings for use in the xml doc
  4192. svgwidth = str(size[0] + (2 * boundary))
  4193. svgheight = str(size[1] + (2 * boundary))
  4194. minx = str(bounds[0] - boundary)
  4195. miny = str(bounds[1] + boundary + size[1])
  4196. self.log.debug(minx)
  4197. self.log.debug(miny)
  4198. # Add a SVG Header and footer to the svg output from shapely
  4199. # The transform flips the Y Axis so that everything renders
  4200. # properly within svg apps such as inkscape
  4201. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4202. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4203. svg_header += 'width="' + svgwidth + uom + '" '
  4204. svg_header += 'height="' + svgheight + uom + '" '
  4205. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4206. svg_header += '>'
  4207. svg_header += '<g transform="scale(1,-1)">'
  4208. svg_footer = '</g> </svg>'
  4209. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4210. self.progress.emit(90)
  4211. # Parse the xml through a xml parser just to add line feeds
  4212. # and to make it look more pretty for the output
  4213. doc = parse_xml_string(svg_elem)
  4214. with open(filename, 'w') as fp:
  4215. fp.write(doc.toprettyxml())
  4216. self.progress.emit(100)
  4217. self.file_saved.emit("SVG", filename)
  4218. self.inform.emit("[success] SVG file exported to " + filename)
  4219. if use_thread is True:
  4220. proc = self.proc_container.new("Generating Film ... Please wait.")
  4221. def job_thread_film(app_obj):
  4222. try:
  4223. make_black_film()
  4224. except Exception as e:
  4225. proc.done()
  4226. return
  4227. proc.done()
  4228. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4229. else:
  4230. make_black_film()
  4231. def export_excellon(self, obj_name, filename, altium_format=None, use_thread=True):
  4232. """
  4233. Exports a Geometry Object to an Excellon file.
  4234. :param filename: Path to the Excellon file to save to.
  4235. :return:
  4236. """
  4237. if filename is None:
  4238. filename = self.defaults["global_last_save_folder"]
  4239. self.log.debug("export_excellon()")
  4240. format_exc = ';FILE_FORMAT=2:4\n'
  4241. units = ''
  4242. try:
  4243. obj = self.collection.get_by_name(str(obj_name))
  4244. except:
  4245. # TODO: The return behavior has not been established... should raise exception?
  4246. return "Could not retrieve object: %s" % obj_name
  4247. # updated units
  4248. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4249. if units == 'IN' or units == 'INCH':
  4250. units = 'INCH'
  4251. elif units == 'MM' or units == 'METRIC':
  4252. units ='METRIC'
  4253. def make_excellon():
  4254. try:
  4255. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4256. header = 'M48\n'
  4257. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4258. (str(self.app.version), str(self.app.version_date))
  4259. header += ';Filename: %s' % str(obj_name) + '\n'
  4260. header += ';Created on : %s' % time_str + '\n'
  4261. if altium_format == None:
  4262. has_slots, excellon_code = obj.export_excellon()
  4263. header += units + '\n'
  4264. for tool in obj.tools:
  4265. if units == 'METRIC':
  4266. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.2f' % float(obj.tools[tool]['C']) + '\n'
  4267. else:
  4268. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4269. else:
  4270. has_slots, excellon_code = obj.export_excellon_altium()
  4271. header += 'INCH,LZ\n'
  4272. header += format_exc
  4273. for tool in obj.tools:
  4274. if units == 'METRIC':
  4275. header += 'T' + str(tool) + 'F00S00' + 'C' + \
  4276. '%.4f' % (float(obj.tools[tool]['C']) / 25.4) + '\n'
  4277. else:
  4278. header += 'T' + str(tool) + 'F00S00' + 'C' + '%.4f' % float(obj.tools[tool]['C']) + '\n'
  4279. header += '%\n'
  4280. footer = 'M30\n'
  4281. exported_excellon = header
  4282. exported_excellon += excellon_code
  4283. exported_excellon += footer
  4284. with open(filename, 'w') as fp:
  4285. fp.write(exported_excellon)
  4286. self.file_saved.emit("Excellon", filename)
  4287. self.inform.emit("[success] Excellon file exported to " + filename)
  4288. except:
  4289. return 'fail'
  4290. if use_thread is True:
  4291. with self.proc_container.new("Exporting Excellon") as proc:
  4292. def job_thread_exc(app_obj):
  4293. ret = make_excellon()
  4294. if ret == 'fail':
  4295. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4296. return
  4297. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4298. else:
  4299. ret = make_excellon()
  4300. if ret == 'fail':
  4301. self.inform.emit('[error_notcl] Could not export Excellon file.')
  4302. return
  4303. def export_dxf(self, obj_name, filename, use_thread=True):
  4304. """
  4305. Exports a Geometry Object to an DXF file.
  4306. :param filename: Path to the DXF file to save to.
  4307. :return:
  4308. """
  4309. if filename is None:
  4310. filename = self.defaults["global_last_save_folder"]
  4311. self.log.debug("export_dxf()")
  4312. format_exc = ''
  4313. units = ''
  4314. try:
  4315. obj = self.collection.get_by_name(str(obj_name))
  4316. except:
  4317. # TODO: The return behavior has not been established... should raise exception?
  4318. return "Could not retrieve object: %s" % obj_name
  4319. # updated units
  4320. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4321. if units == 'IN' or units == 'INCH':
  4322. units = 'INCH'
  4323. elif units == 'MM' or units == 'METIRC':
  4324. units ='METRIC'
  4325. def make_dxf():
  4326. try:
  4327. dxf_code = obj.export_dxf()
  4328. dxf_code.saveas(filename)
  4329. self.file_saved.emit("DXF", filename)
  4330. self.inform.emit("[success] DXF file exported to " + filename)
  4331. except:
  4332. return 'fail'
  4333. if use_thread is True:
  4334. with self.proc_container.new("Exporting DXF") as proc:
  4335. def job_thread_exc(app_obj):
  4336. ret = make_dxf()
  4337. if ret == 'fail':
  4338. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4339. return
  4340. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4341. else:
  4342. ret = make_dxf()
  4343. if ret == 'fail':
  4344. self.inform.emit('[[warning_notcl]] Could not export DXF file.')
  4345. return
  4346. def import_svg(self, filename, geo_type='geometry', outname=None):
  4347. """
  4348. Adds a new Geometry Object to the projects and populates
  4349. it with shapes extracted from the SVG file.
  4350. :param filename: Path to the SVG file.
  4351. :param outname:
  4352. :return:
  4353. """
  4354. obj_type = ""
  4355. if geo_type is None or geo_type == "geometry":
  4356. obj_type = "geometry"
  4357. elif geo_type == "gerber":
  4358. obj_type = geo_type
  4359. else:
  4360. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4361. "Only Geometry and Gerber are supported")
  4362. return
  4363. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4364. def obj_init(geo_obj, app_obj):
  4365. geo_obj.import_svg(filename, obj_type, units=units)
  4366. geo_obj.multigeo = False
  4367. with self.proc_container.new("Importing SVG") as proc:
  4368. # Object name
  4369. name = outname or filename.split('/')[-1].split('\\')[-1]
  4370. self.new_object(obj_type, name, obj_init, autoselected=False)
  4371. self.progress.emit(20)
  4372. # Register recent file
  4373. self.file_opened.emit("svg", filename)
  4374. # GUI feedback
  4375. self.inform.emit("[success] Opened: " + filename)
  4376. self.progress.emit(100)
  4377. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4378. """
  4379. Adds a new Geometry Object to the projects and populates
  4380. it with shapes extracted from the DXF file.
  4381. :param filename: Path to the DXF file.
  4382. :param outname:
  4383. :type putname: str
  4384. :return:
  4385. """
  4386. obj_type = ""
  4387. if geo_type is None or geo_type == "geometry":
  4388. obj_type = "geometry"
  4389. elif geo_type == "gerber":
  4390. obj_type = geo_type
  4391. else:
  4392. self.inform.emit("[error_notcl] Not supported type was choosed as parameter. "
  4393. "Only Geometry and Gerber are supported")
  4394. return
  4395. units = self.general_options_form.general_app_group.units_radio.get_value().upper()
  4396. def obj_init(geo_obj, app_obj):
  4397. geo_obj.import_dxf(filename, obj_type, units=units)
  4398. geo_obj.multigeo = False
  4399. with self.proc_container.new("Importing DXF") as proc:
  4400. # Object name
  4401. name = outname or filename.split('/')[-1].split('\\')[-1]
  4402. self.new_object(obj_type, name, obj_init, autoselected=False)
  4403. self.progress.emit(20)
  4404. # Register recent file
  4405. self.file_opened.emit("dxf", filename)
  4406. # GUI feedback
  4407. self.inform.emit("[success] Opened: " + filename)
  4408. self.progress.emit(100)
  4409. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4410. """
  4411. Adds a new Geometry Object to the projects and populates
  4412. it with shapes extracted from the SVG file.
  4413. :param filename: Path to the SVG file.
  4414. :param outname:
  4415. :return:
  4416. """
  4417. obj_type = ""
  4418. if type is None or type == "geometry":
  4419. obj_type = "geometry"
  4420. elif type == "gerber":
  4421. obj_type = type
  4422. else:
  4423. self.inform.emit("[error_notcl] Not supported type was picked as parameter. "
  4424. "Only Geometry and Gerber are supported")
  4425. return
  4426. def obj_init(geo_obj, app_obj):
  4427. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  4428. geo_obj.multigeo = False
  4429. with self.proc_container.new("Importing Image") as proc:
  4430. # Object name
  4431. name = outname or filename.split('/')[-1].split('\\')[-1]
  4432. units = self.general_options_form.general_app_group.units_radio.get_value()
  4433. self.new_object(obj_type, name, obj_init)
  4434. self.progress.emit(20)
  4435. # Register recent file
  4436. self.file_opened.emit("image", filename)
  4437. # GUI feedback
  4438. self.inform.emit("[success] Opened: " + filename)
  4439. self.progress.emit(100)
  4440. def open_gerber(self, filename, follow=False, outname=None):
  4441. """
  4442. Opens a Gerber file, parses it and creates a new object for
  4443. it in the program. Thread-safe.
  4444. :param outname: Name of the resulting object. None causes the
  4445. name to be that of the file.
  4446. :param filename: Gerber file filename
  4447. :type filename: str
  4448. :param follow: If true, the parser will not create polygons, just lines
  4449. following the gerber path.
  4450. :type follow: bool
  4451. :return: None
  4452. """
  4453. # How the object should be initialized
  4454. def obj_init(gerber_obj, app_obj):
  4455. assert isinstance(gerber_obj, FlatCAMGerber), \
  4456. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  4457. # Opening the file happens here
  4458. self.progress.emit(30)
  4459. try:
  4460. gerber_obj.parse_file(filename, follow=follow)
  4461. except IOError:
  4462. app_obj.inform.emit("[error_notcl] Failed to open file: " + filename)
  4463. app_obj.progress.emit(0)
  4464. self.inform.emit('[error_notcl] Failed to open file: ' + filename)
  4465. return "fail"
  4466. except ParseError as err:
  4467. app_obj.inform.emit("[error_notcl] Failed to parse file: " + filename + ". " + str(err))
  4468. app_obj.progress.emit(0)
  4469. self.log.error(str(err))
  4470. return "fail"
  4471. except:
  4472. msg = "[error] An internal error has ocurred. See shell.\n"
  4473. msg += traceback.format_exc()
  4474. app_obj.inform.emit(msg)
  4475. return "fail"
  4476. if gerber_obj.is_empty():
  4477. # app_obj.inform.emit("[error] No geometry found in file: " + filename)
  4478. # self.collection.set_active(gerber_obj.options["name"])
  4479. # self.collection.delete_active()
  4480. self.inform.emit("[error_notcl] Object is not Gerber file or empty. Aborting object creation.")
  4481. return "fail"
  4482. # Further parsing
  4483. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  4484. if follow is False:
  4485. App.log.debug("open_gerber()")
  4486. else:
  4487. App.log.debug("open_gerber() with 'follow' attribute")
  4488. with self.proc_container.new("Opening Gerber") as proc:
  4489. self.progress.emit(10)
  4490. # Object name
  4491. name = outname or filename.split('/')[-1].split('\\')[-1]
  4492. ### Object creation ###
  4493. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  4494. if ret == 'fail':
  4495. self.inform.emit('[error_notcl] Open Gerber failed. Probable not a Gerber file.')
  4496. return
  4497. # Register recent file
  4498. self.file_opened.emit("gerber", filename)
  4499. self.progress.emit(100)
  4500. # GUI feedback
  4501. self.inform.emit("[success] Opened: " + filename)
  4502. def open_excellon(self, filename, outname=None):
  4503. """
  4504. Opens an Excellon file, parses it and creates a new object for
  4505. it in the program. Thread-safe.
  4506. :param outname: Name of the resulting object. None causes the
  4507. name to be that of the file.
  4508. :param filename: Excellon file filename
  4509. :type filename: str
  4510. :return: None
  4511. """
  4512. App.log.debug("open_excellon()")
  4513. #self.progress.emit(10)
  4514. # How the object should be initialized
  4515. def obj_init(excellon_obj, app_obj):
  4516. # self.progress.emit(20)
  4517. try:
  4518. ret = excellon_obj.parse_file(filename)
  4519. if ret == "fail":
  4520. log.debug("Excellon parsing failed.")
  4521. self.inform.emit("[error_notcl] This is not Excellon file.")
  4522. return "fail"
  4523. except IOError:
  4524. app_obj.inform.emit("[error_notcl] Cannot open file: " + filename)
  4525. log.debug("Could not open Excellon object.")
  4526. self.progress.emit(0) # TODO: self and app_bjj mixed
  4527. return "fail"
  4528. except:
  4529. msg = "[error_notcl] An internal error has occurred. See shell.\n"
  4530. msg += traceback.format_exc()
  4531. app_obj.inform.emit(msg)
  4532. return "fail"
  4533. ret = excellon_obj.create_geometry()
  4534. if ret == 'fail':
  4535. log.debug("Could not create geometry for Excellon object.")
  4536. return "fail"
  4537. if excellon_obj.is_empty():
  4538. app_obj.inform.emit("[error_notcl] No geometry found in file: " + filename)
  4539. return "fail"
  4540. with self.proc_container.new("Opening Excellon."):
  4541. # Object name
  4542. name = outname or filename.split('/')[-1].split('\\')[-1]
  4543. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  4544. if ret == 'fail':
  4545. self.inform.emit('[error_notcl] Open Excellon file failed. Probable not an Excellon file.')
  4546. return
  4547. # Register recent file
  4548. self.file_opened.emit("excellon", filename)
  4549. # GUI feedback
  4550. self.inform.emit("[success] Opened: " + filename)
  4551. # self.progress.emit(100)
  4552. def open_gcode(self, filename, outname=None):
  4553. """
  4554. Opens a G-gcode file, parses it and creates a new object for
  4555. it in the program. Thread-safe.
  4556. :param outname: Name of the resulting object. None causes the
  4557. name to be that of the file.
  4558. :param filename: G-code file filename
  4559. :type filename: str
  4560. :return: None
  4561. """
  4562. App.log.debug("open_gcode()")
  4563. # How the object should be initialized
  4564. def obj_init(job_obj, app_obj_):
  4565. """
  4566. :type app_obj_: App
  4567. """
  4568. assert isinstance(app_obj_, App), \
  4569. "Initializer expected App, got %s" % type(app_obj_)
  4570. self.progress.emit(10)
  4571. try:
  4572. f = open(filename)
  4573. gcode = f.read()
  4574. f.close()
  4575. except IOError:
  4576. app_obj_.inform.emit("[error_notcl] Failed to open " + filename)
  4577. self.progress.emit(0)
  4578. return "fail"
  4579. job_obj.gcode = gcode
  4580. self.progress.emit(20)
  4581. ret = job_obj.gcode_parse()
  4582. if ret == "fail":
  4583. self.inform.emit("[error_notcl] This is not GCODE")
  4584. return "fail"
  4585. self.progress.emit(60)
  4586. job_obj.create_geometry()
  4587. with self.proc_container.new("Opening G-Code."):
  4588. # Object name
  4589. name = outname or filename.split('/')[-1].split('\\')[-1]
  4590. # New object creation and file processing
  4591. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  4592. if ret == 'fail':
  4593. self.inform.emit("[error_notcl] Failed to create CNCJob Object. Probable not a GCode file.\n "
  4594. "Attempting to create a FlatCAM CNCJob Object from "
  4595. "G-Code file failed during processing")
  4596. return "fail"
  4597. # Register recent file
  4598. self.file_opened.emit("cncjob", filename)
  4599. # GUI feedback
  4600. self.inform.emit("[success] Opened: " + filename)
  4601. self.progress.emit(100)
  4602. def open_project(self, filename, run_from_arg=None):
  4603. """
  4604. Loads a project from the specified file.
  4605. 1) Loads and parses file
  4606. 2) Registers the file as recently opened.
  4607. 3) Calls on_file_new()
  4608. 4) Updates options
  4609. 5) Calls new_object() with the object's from_dict() as init method.
  4610. 6) Calls plot_all()
  4611. :param filename: Name of the file from which to load.
  4612. :type filename: str
  4613. :return: None
  4614. """
  4615. App.log.debug("Opening project: " + filename)
  4616. # Open and parse
  4617. try:
  4618. f = open(filename, 'r')
  4619. except IOError:
  4620. App.log.error("Failed to open project file: %s" % filename)
  4621. self.inform.emit("[error_notcl] Failed to open project file: %s" % filename)
  4622. return
  4623. try:
  4624. d = json.load(f, object_hook=dict2obj)
  4625. except:
  4626. App.log.error("Failed to parse project file: %s" % filename)
  4627. self.inform.emit("[error_notcl] Failed to parse project file: %s" % filename)
  4628. f.close()
  4629. return
  4630. self.file_opened.emit("project", filename)
  4631. # Clear the current project
  4632. ## NOT THREAD SAFE ##
  4633. if run_from_arg is True:
  4634. pass
  4635. else:
  4636. self.on_file_new()
  4637. #Project options
  4638. self.options.update(d['options'])
  4639. self.project_filename = filename
  4640. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4641. self.set_screen_units(self.options["units"])
  4642. # Re create objects
  4643. App.log.debug("Re-creating objects...")
  4644. for obj in d['objs']:
  4645. def obj_init(obj_inst, app_inst):
  4646. obj_inst.from_dict(obj)
  4647. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  4648. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  4649. # self.plot_all()
  4650. self.inform.emit("[success] Project loaded from: " + filename)
  4651. App.log.debug("Project loaded")
  4652. def propagate_defaults(self, silent=False):
  4653. """
  4654. This method is used to set default values in classes. It's
  4655. an alternative to project options but allows the use
  4656. of values invisible to the user.
  4657. :return: None
  4658. """
  4659. if silent is False:
  4660. self.log.debug("propagate_defaults()")
  4661. # Which objects to update the given parameters.
  4662. routes = {
  4663. "global_zdownrate": CNCjob,
  4664. "excellon_zeros": Excellon,
  4665. "excellon_format_upper_in": Excellon,
  4666. "excellon_format_lower_in": Excellon,
  4667. "excellon_format_upper_mm": Excellon,
  4668. "excellon_format_lower_mm": Excellon,
  4669. "excellon_units": Excellon,
  4670. "gerber_use_buffer_for_union": Gerber,
  4671. "geometry_multidepth": Geometry
  4672. }
  4673. for param in routes:
  4674. if param in routes[param].defaults:
  4675. try:
  4676. routes[param].defaults[param] = self.defaults[param]
  4677. if silent is False:
  4678. self.log.debug(" " + param + " OK")
  4679. except KeyError:
  4680. if silent is False:
  4681. self.log.debug(" ERROR: " + param + " not in defaults.")
  4682. else:
  4683. # Try extracting the name:
  4684. # classname_param here is param in the object
  4685. if param.find(routes[param].__name__.lower() + "_") == 0:
  4686. p = param[len(routes[param].__name__) + 1:]
  4687. if p in routes[param].defaults:
  4688. routes[param].defaults[p] = self.defaults[param]
  4689. if silent is False:
  4690. self.log.debug(" " + param + " OK!")
  4691. def restore_main_win_geom(self):
  4692. try:
  4693. self.ui.setGeometry(self.defaults["global_def_win_x"],
  4694. self.defaults["global_def_win_y"],
  4695. self.defaults["global_def_win_w"],
  4696. self.defaults["global_def_win_h"])
  4697. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  4698. except KeyError:
  4699. pass
  4700. def plot_all(self):
  4701. """
  4702. Re-generates all plots from all objects.
  4703. :return: None
  4704. """
  4705. self.log.debug("Plot_all()")
  4706. for obj in self.collection.get_list():
  4707. def worker_task(obj):
  4708. with self.proc_container.new("Plotting"):
  4709. obj.plot()
  4710. self.object_plotted.emit(obj)
  4711. # Send to worker
  4712. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  4713. # self.progress.emit(10)
  4714. #
  4715. # def worker_task(app_obj):
  4716. # print "worker task"
  4717. # percentage = 0.1
  4718. # try:
  4719. # delta = 0.9 / len(self.collection.get_list())
  4720. # except ZeroDivisionError:
  4721. # self.progress.emit(0)
  4722. # return
  4723. # for obj in self.collection.get_list():
  4724. # with self.proc_container.new("Plotting"):
  4725. # obj.plot()
  4726. # app_obj.object_plotted.emit(obj)
  4727. #
  4728. # percentage += delta
  4729. # self.progress.emit(int(percentage*100))
  4730. #
  4731. # self.progress.emit(0)
  4732. # self.plots_updated.emit()
  4733. #
  4734. # # Send to worker
  4735. # #self.worker.add_task(worker_task, [self])
  4736. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  4737. def register_folder(self, filename):
  4738. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  4739. def register_save_folder(self, filename):
  4740. self.defaults['global_last_save_folder'] = os.path.split(str(filename))[0]
  4741. def set_progress_bar(self, percentage, text=""):
  4742. self.ui.progress_bar.setValue(int(percentage))
  4743. def setup_shell(self):
  4744. """
  4745. Creates shell functions. Runs once at startup.
  4746. :return: None
  4747. """
  4748. self.log.debug("setup_shell()")
  4749. def shelp(p=None):
  4750. if not p:
  4751. return "Available commands:\n" + \
  4752. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  4753. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  4754. if p not in commands:
  4755. return "Unknown command: %s" % p
  4756. return commands[p]["help"]
  4757. # --- Migrated to new architecture ---
  4758. # def options(name):
  4759. # ops = self.collection.get_by_name(str(name)).options
  4760. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  4761. def h(*args):
  4762. """
  4763. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  4764. and standalone parameters into list.
  4765. """
  4766. kwa = {}
  4767. a = []
  4768. n = len(args)
  4769. name = None
  4770. for i in range(n):
  4771. match = re.search(r'^-([a-zA-Z].*)', args[i])
  4772. if match:
  4773. assert name is None
  4774. name = match.group(1)
  4775. continue
  4776. if name is None:
  4777. a.append(args[i])
  4778. else:
  4779. kwa[name] = args[i]
  4780. name = None
  4781. return a, kwa
  4782. @contextmanager
  4783. def wait_signal(signal, timeout=10000):
  4784. """
  4785. Block loop until signal emitted, timeout (ms) elapses
  4786. or unhandled exception happens in a thread.
  4787. :param signal: Signal to wait for.
  4788. """
  4789. loop = QtCore.QEventLoop()
  4790. # Normal termination
  4791. signal.connect(loop.quit)
  4792. # Termination by exception in thread
  4793. self.thread_exception.connect(loop.quit)
  4794. status = {'timed_out': False}
  4795. def report_quit():
  4796. status['timed_out'] = True
  4797. loop.quit()
  4798. yield
  4799. # Temporarily change how exceptions are managed.
  4800. oeh = sys.excepthook
  4801. ex = []
  4802. def except_hook(type_, value, traceback_):
  4803. ex.append(value)
  4804. oeh(type_, value, traceback_)
  4805. sys.excepthook = except_hook
  4806. # Terminate on timeout
  4807. if timeout is not None:
  4808. QtCore.QTimer.singleShot(timeout, report_quit)
  4809. #### Block ####
  4810. loop.exec_()
  4811. # Restore exception management
  4812. sys.excepthook = oeh
  4813. if ex:
  4814. self.raiseTclError(str(ex[0]))
  4815. if status['timed_out']:
  4816. raise Exception('Timed out!')
  4817. def make_docs():
  4818. output = ''
  4819. import collections
  4820. od = collections.OrderedDict(sorted(commands.items()))
  4821. for cmd_, val in od.items():
  4822. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  4823. t = val['help']
  4824. usage_i = t.find('>')
  4825. if usage_i < 0:
  4826. expl = t
  4827. output += expl + '\n\n'
  4828. continue
  4829. expl = t[:usage_i - 1]
  4830. output += expl + '\n\n'
  4831. end_usage_i = t[usage_i:].find('\n')
  4832. if end_usage_i < 0:
  4833. end_usage_i = len(t[usage_i:])
  4834. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  4835. else:
  4836. extras = t[usage_i+end_usage_i+1:]
  4837. parts = [s.strip() for s in extras.split('\n')]
  4838. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  4839. for p in parts:
  4840. output += ' ' + p + '\n\n'
  4841. return output
  4842. '''
  4843. Howto implement TCL shell commands:
  4844. All parameters passed to command should be possible to set as None and test it afterwards.
  4845. This is because we need to see error caused in tcl,
  4846. if None value as default parameter is not allowed TCL will return empty error.
  4847. Use:
  4848. def mycommand(name=None,...):
  4849. Test it like this:
  4850. if name is None:
  4851. self.raise_tcl_error('Argument name is missing.')
  4852. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  4853. otherwise we will miss it and processing will silently continue.
  4854. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  4855. which is catched in exec_command and displayed in TCL shell console with red background.
  4856. Error in console is displayed with TCL trace.
  4857. This behavior works only within main thread,
  4858. errors with promissed tasks can be catched and detected only with log.
  4859. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  4860. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  4861. '''
  4862. commands = {
  4863. 'help': {
  4864. 'fcn': shelp,
  4865. 'help': "Shows list of commands."
  4866. },
  4867. }
  4868. # Import/overwrite tcl commands as objects of TclCommand descendants
  4869. # This modifies the variable 'commands'.
  4870. tclCommands.register_all_commands(self, commands)
  4871. # Add commands to the tcl interpreter
  4872. for cmd in commands:
  4873. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  4874. # Make the tcl puts function return instead of print to stdout
  4875. self.tcl.eval('''
  4876. rename puts original_puts
  4877. proc puts {args} {
  4878. if {[llength $args] == 1} {
  4879. return "[lindex $args 0]"
  4880. } else {
  4881. eval original_puts $args
  4882. }
  4883. }
  4884. ''')
  4885. def setup_recent_items(self):
  4886. # TODO: Move this to constructor
  4887. icons = {
  4888. "gerber": "share/flatcam_icon16.png",
  4889. "excellon": "share/drill16.png",
  4890. "cncjob": "share/cnc16.png",
  4891. "project": "share/project16.png",
  4892. "svg": "share/geometry16.png",
  4893. "dxf": "share/dxf16.png",
  4894. "image": "share/image16.png"
  4895. }
  4896. openers = {
  4897. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  4898. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  4899. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  4900. 'project': self.open_project,
  4901. 'svg': self.import_svg,
  4902. 'dxf': self.import_dxf,
  4903. 'image': self.import_image
  4904. }
  4905. # Open file
  4906. try:
  4907. f = open(self.data_path + '/recent.json')
  4908. except IOError:
  4909. App.log.error("Failed to load recent item list.")
  4910. self.inform.emit("[error_notcl] Failed to load recent item list.")
  4911. return
  4912. try:
  4913. self.recent = json.load(f)
  4914. except json.scanner.JSONDecodeError:
  4915. App.log.error("Failed to parse recent item list.")
  4916. self.inform.emit("[error_notcl] Failed to parse recent item list.")
  4917. f.close()
  4918. return
  4919. f.close()
  4920. # Closure needed to create callbacks in a loop.
  4921. # Otherwise late binding occurs.
  4922. def make_callback(func, fname):
  4923. def opener():
  4924. func(fname)
  4925. return opener
  4926. def reset_recent():
  4927. # Reset menu
  4928. self.ui.recent.clear()
  4929. self.recent = []
  4930. try:
  4931. f = open(self.data_path + '/recent.json', 'w')
  4932. except IOError:
  4933. App.log.error("Failed to open recent items file for writing.")
  4934. return
  4935. json.dump(self.recent, f)
  4936. # Reset menu
  4937. self.ui.recent.clear()
  4938. # Create menu items
  4939. for recent in self.recent:
  4940. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  4941. try:
  4942. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  4943. # Attach callback
  4944. o = make_callback(openers[recent["kind"]], recent['filename'])
  4945. action.triggered.connect(o)
  4946. self.ui.recent.addAction(action)
  4947. except KeyError:
  4948. App.log.error("Unsupported file type: %s" % recent["kind"])
  4949. # Last action in Recent Files menu is one that Clear the content
  4950. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  4951. clear_action.triggered.connect(reset_recent)
  4952. self.ui.recent.addSeparator()
  4953. self.ui.recent.addAction(clear_action)
  4954. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  4955. # self.ui.menufilerecent.set_submenu(recent_menu)
  4956. # recent_menu.show_all()
  4957. # self.ui.recent.show()
  4958. self.log.debug("Recent items list has been populated.")
  4959. def setup_component_editor(self):
  4960. label = QtWidgets.QLabel("Choose an item from Project")
  4961. label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  4962. self.ui.selected_scroll_area.setWidget(label)
  4963. def setup_obj_classes(self):
  4964. """
  4965. Sets up application specifics on the FlatCAMObj class.
  4966. :return: None
  4967. """
  4968. FlatCAMObj.app = self
  4969. ObjectCollection.app = self
  4970. FCProcess.app = self
  4971. FCProcessContainer.app = self
  4972. def version_check(self):
  4973. """
  4974. Checks for the latest version of the program. Alerts the
  4975. user if theirs is outdated. This method is meant to be run
  4976. in a separate thread.
  4977. :return: None
  4978. """
  4979. self.log.debug("version_check()")
  4980. if self.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  4981. full_url = App.version_url + \
  4982. "?s=" + str(self.defaults['global_serial']) + \
  4983. "&v=" + str(self.version) + \
  4984. "&os=" + str(self.os) + \
  4985. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  4986. else:
  4987. # no_stats dict; just so it won't break things on website
  4988. no_ststs_dict = {}
  4989. no_ststs_dict["global_ststs"] = {}
  4990. full_url = App.version_url + \
  4991. "?s=" + str(self.defaults['global_serial']) + \
  4992. "&v=" + str(self.version) + \
  4993. "&os=" + str(self.os) + \
  4994. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  4995. App.log.debug("Checking for updates @ %s" % full_url)
  4996. ### Get the data
  4997. try:
  4998. f = urllib.request.urlopen(full_url)
  4999. except:
  5000. # App.log.warning("Failed checking for latest version. Could not connect.")
  5001. self.log.warning("Failed checking for latest version. Could not connect.")
  5002. self.inform.emit("[warning_notcl] Failed checking for latest version. Could not connect.")
  5003. return
  5004. try:
  5005. data = json.load(f)
  5006. except Exception as e:
  5007. App.log.error("Could not parse information about latest version.")
  5008. self.inform.emit("[error_notcl] Could not parse information about latest version.")
  5009. App.log.debug("json.load(): %s" % str(e))
  5010. f.close()
  5011. return
  5012. f.close()
  5013. ### Latest version?
  5014. if self.version >= data["version"]:
  5015. App.log.debug("FlatCAM is up to date!")
  5016. self.inform.emit("[success] FlatCAM is up to date!")
  5017. return
  5018. App.log.debug("Newer version available.")
  5019. self.message.emit(
  5020. "Newer Version Available",
  5021. str("There is a newer version of FlatCAM " +
  5022. "available for download:<br><br>" +
  5023. "<B>" + data["name"] + "</b><br>" +
  5024. data["message"].replace("\n", "<br>")),
  5025. "info"
  5026. )
  5027. # TODO: FIX THIS
  5028. '''
  5029. By default this is not threaded
  5030. If threaded the app give warnings like this:
  5031. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5032. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5033. '''
  5034. def enable_plots(self, objects, threaded=False):
  5035. if threaded is True:
  5036. def worker_task(app_obj):
  5037. percentage = 0.1
  5038. try:
  5039. delta = 0.9 / len(objects)
  5040. except ZeroDivisionError:
  5041. self.progress.emit(0)
  5042. return
  5043. for obj in objects:
  5044. obj.options['plot'] = True
  5045. percentage += delta
  5046. self.progress.emit(int(percentage*100))
  5047. self.progress.emit(0)
  5048. self.plots_updated.emit()
  5049. self.collection.update_view()
  5050. # Send to worker
  5051. # self.worker.add_task(worker_task, [self])
  5052. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5053. else:
  5054. for obj in objects:
  5055. obj.options['plot'] = True
  5056. self.progress.emit(0)
  5057. self.plots_updated.emit()
  5058. self.collection.update_view()
  5059. # TODO: FIX THIS
  5060. '''
  5061. By default this is not threaded
  5062. If threaded the app give warnings like this:
  5063. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5064. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5065. '''
  5066. def disable_plots(self, objects, threaded=False):
  5067. # TODO: This method is very similar to replot_all. Try to merge.
  5068. """
  5069. Disables plots
  5070. :param objects: list
  5071. Objects to be disabled
  5072. :return:
  5073. """
  5074. if threaded is True:
  5075. self.progress.emit(10)
  5076. def worker_task(app_obj):
  5077. percentage = 0.1
  5078. try:
  5079. delta = 0.9 / len(objects)
  5080. except ZeroDivisionError:
  5081. self.progress.emit(0)
  5082. return
  5083. for obj in objects:
  5084. obj.options['plot'] = False
  5085. percentage += delta
  5086. self.progress.emit(int(percentage*100))
  5087. self.progress.emit(0)
  5088. self.plots_updated.emit()
  5089. self.collection.update_view()
  5090. # Send to worker
  5091. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5092. else:
  5093. for obj in objects:
  5094. obj.options['plot'] = False
  5095. self.plots_updated.emit()
  5096. self.collection.update_view()
  5097. def clear_plots(self):
  5098. objects = self.collection.get_list()
  5099. for obj in objects:
  5100. obj.clear(obj == objects[-1])
  5101. # Clear pool to free memory
  5102. self.clear_pool()
  5103. def generate_cnc_job(self, objects):
  5104. for obj in objects:
  5105. obj.generatecncjob()
  5106. def save_project(self, filename):
  5107. """
  5108. Saves the current project to the specified file.
  5109. :param filename: Name of the file in which to save.
  5110. :type filename: str
  5111. :return: None
  5112. """
  5113. self.log.debug("save_project()")
  5114. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5115. ## Capture the latest changes
  5116. # Current object
  5117. try:
  5118. self.collection.get_active().read_form()
  5119. except:
  5120. self.log.debug("[warning] There was no active object")
  5121. pass
  5122. # Project options
  5123. self.options_read_form()
  5124. # Serialize the whole project
  5125. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5126. "options": self.options,
  5127. "version": self.version}
  5128. # Open file
  5129. try:
  5130. f = open(filename, 'w')
  5131. except IOError:
  5132. App.log.error("[error] Failed to open file for saving: %s", filename)
  5133. return
  5134. # Write
  5135. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5136. f.close()
  5137. # verification of the saved project
  5138. # Open and parse
  5139. try:
  5140. saved_f = open(filename, 'r')
  5141. except IOError:
  5142. self.inform.emit("[error_notcl] Failed to verify project file: %s. Retry to save it." % filename)
  5143. return
  5144. try:
  5145. saved_d = json.load(saved_f, object_hook=dict2obj)
  5146. except:
  5147. self.inform.emit("[error_notcl] Failed to parse saved project file: %s. Retry to save it." % filename)
  5148. f.close()
  5149. return
  5150. saved_f.close()
  5151. if 'version' in saved_d:
  5152. self.inform.emit("[success] Project saved to: %s" % filename)
  5153. else:
  5154. self.inform.emit("[error_notcl] Failed to save project file: %s. Retry to save it." % filename)
  5155. def on_options_app2project(self):
  5156. """
  5157. Callback for Options->Transfer Options->App=>Project. Copies options
  5158. from application defaults to project defaults.
  5159. :return: None
  5160. """
  5161. self.report_usage("on_options_app2project")
  5162. self.defaults_read_form()
  5163. self.options.update(self.defaults)
  5164. self.options_write_form()
  5165. def on_options_project2app(self):
  5166. """
  5167. Callback for Options->Transfer Options->Project=>App. Copies options
  5168. from project defaults to application defaults.
  5169. :return: None
  5170. """
  5171. self.report_usage("on_options_project2app")
  5172. self.options_read_form()
  5173. self.defaults.update(self.options)
  5174. self.defaults_write_form()
  5175. def on_options_project2object(self):
  5176. """
  5177. Callback for Options->Transfer Options->Project=>Object. Copies options
  5178. from project defaults to the currently selected object.
  5179. :return: None
  5180. """
  5181. self.report_usage("on_options_project2object")
  5182. self.options_read_form()
  5183. obj = self.collection.get_active()
  5184. if obj is None:
  5185. self.inform.emit("WARNING: No object selected.")
  5186. return
  5187. for option in self.options:
  5188. if option.find(obj.kind + "_") == 0:
  5189. oname = option[len(obj.kind) + 1:]
  5190. obj.options[oname] = self.options[option]
  5191. obj.to_form() # Update UI
  5192. def on_options_object2project(self):
  5193. """
  5194. Callback for Options->Transfer Options->Object=>Project. Copies options
  5195. from the currently selected object to project defaults.
  5196. :return: None
  5197. """
  5198. self.report_usage("on_options_object2project")
  5199. obj = self.collection.get_active()
  5200. if obj is None:
  5201. self.inform.emit("WARNING: No object selected.")
  5202. return
  5203. obj.read_form()
  5204. for option in obj.options:
  5205. if option in ['name']: # TODO: Handle this better...
  5206. continue
  5207. self.options[obj.kind + "_" + option] = obj.options[option]
  5208. self.options_write_form()
  5209. def on_options_object2app(self):
  5210. """
  5211. Callback for Options->Transfer Options->Object=>App. Copies options
  5212. from the currently selected object to application defaults.
  5213. :return: None
  5214. """
  5215. self.report_usage("on_options_object2app")
  5216. obj = self.collection.get_active()
  5217. if obj is None:
  5218. self.inform.emit("WARNING: No object selected.")
  5219. return
  5220. obj.read_form()
  5221. for option in obj.options:
  5222. if option in ['name']: # TODO: Handle this better...
  5223. continue
  5224. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5225. self.defaults_write_form()
  5226. def on_options_app2object(self):
  5227. """
  5228. Callback for Options->Transfer Options->App=>Object. Copies options
  5229. from application defaults to the currently selected object.
  5230. :return: None
  5231. """
  5232. self.report_usage("on_options_app2object")
  5233. self.defaults_read_form()
  5234. obj = self.collection.get_active()
  5235. if obj is None:
  5236. self.inform.emit("WARNING: No object selected.")
  5237. return
  5238. for option in self.defaults:
  5239. if option.find(obj.kind + "_") == 0:
  5240. oname = option[len(obj.kind) + 1:]
  5241. obj.options[oname] = self.defaults[option]
  5242. obj.to_form() # Update UI
  5243. # end of file