FlatCAMApp.py 264 KB

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