FlatCAMApp.py 262 KB

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