FlatCAMApp.py 280 KB

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