FlatCAMApp.py 514 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423
  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 urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import threading
  16. import shutil
  17. from stat import S_IREAD, S_IRGRP, S_IROTH
  18. import subprocess
  19. import ctypes
  20. import tkinter as tk
  21. from PyQt5 import QtPrintSupport
  22. from contextlib import contextmanager
  23. import gc
  24. from xml.dom.minidom import parseString as parse_xml_string
  25. from multiprocessing.connection import Listener, Client
  26. from multiprocessing import Pool
  27. import socket
  28. from array import array
  29. # #######################################
  30. # # Imports part of FlatCAM ##
  31. # #######################################
  32. from ObjectCollection import *
  33. from FlatCAMObj import *
  34. from flatcamGUI.PlotCanvas import *
  35. from flatcamGUI.PlotCanvasLegacy import *
  36. from flatcamGUI.FlatCAMGUI import *
  37. from FlatCAMCommon import LoudDict
  38. from FlatCAMPostProc import load_postprocessors
  39. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  40. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  41. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  42. from FlatCAMProcess import *
  43. from FlatCAMWorkerStack import WorkerStack
  44. from flatcamGUI.VisPyVisuals import Color
  45. from vispy.gloo.util import _screenshot
  46. from vispy.io import write_png
  47. from flatcamTools import *
  48. import tclCommands
  49. import gettext
  50. import FlatCAMTranslation as fcTranslate
  51. import builtins
  52. if sys.platform == 'win32':
  53. import winreg
  54. fcTranslate.apply_language('strings')
  55. if '_' not in builtins.__dict__:
  56. _ = gettext.gettext
  57. # ########################################
  58. # # App ###
  59. # ########################################
  60. class App(QtCore.QObject):
  61. """
  62. The main application class. The constructor starts the GUI.
  63. """
  64. # Get Cmd Line Options
  65. cmd_line_shellfile = ''
  66. cmd_line_shellvar = ''
  67. cmd_line_headless = None
  68. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  69. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  70. "FlatCam.py --headless=1"
  71. try:
  72. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  73. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  74. "shellvar=",
  75. "headless=",
  76. "multiprocessing-fork="])
  77. except getopt.GetoptError:
  78. print(cmd_line_help)
  79. sys.exit(2)
  80. for opt, arg in cmd_line_options:
  81. if opt == '-h':
  82. print(cmd_line_help)
  83. sys.exit()
  84. elif opt == '--shellfile':
  85. cmd_line_shellfile = arg
  86. elif opt == '--shellvar':
  87. cmd_line_shellvar = arg
  88. elif opt == '--headless':
  89. try:
  90. cmd_line_headless = eval(arg)
  91. except NameError:
  92. pass
  93. # ## Logging ###
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ##########################################################################
  102. # ################## Version and VERSION DATE ##############################
  103. # ##########################################################################
  104. version = 8.97
  105. version_date = "2019/09/20"
  106. beta = True
  107. # current date now
  108. date = str(datetime.today()).rpartition('.')[0]
  109. date = ''.join(c for c in date if c not in ':-')
  110. date = date.replace(' ', '_')
  111. # URL for update checks and statistics
  112. version_url = "http://flatcam.org/version"
  113. # App URL
  114. app_url = "http://flatcam.org"
  115. # Manual URL
  116. manual_url = "http://flatcam.org/manual/index.html"
  117. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  118. gerber_spec_url ="https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  119. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  120. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  121. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  122. # this variable will hold the project status
  123. # if True it will mean that the project was modified and not saved
  124. should_we_save = False
  125. # flag is True if saving action has been triggered
  126. save_in_progress = False
  127. # ###########################################################################
  128. # ############################# Signals ################################
  129. # ###########################################################################
  130. # Inform the user
  131. # Handled by:
  132. # * App.info() --> Print on the status bar
  133. inform = QtCore.pyqtSignal(str)
  134. app_quit = QtCore.pyqtSignal()
  135. # General purpose background task
  136. worker_task = QtCore.pyqtSignal(dict)
  137. # File opened
  138. # Handled by:
  139. # * register_folder()
  140. # * register_recent()
  141. # Note: Setting the parameters to unicode does not seem
  142. # to have an effect. Then are received as Qstring
  143. # anyway.
  144. # File type and filename
  145. file_opened = QtCore.pyqtSignal(str, str)
  146. # File type and filename
  147. file_saved = QtCore.pyqtSignal(str, str)
  148. # Percentage of progress
  149. progress = QtCore.pyqtSignal(int)
  150. plots_updated = QtCore.pyqtSignal()
  151. # Emitted by new_object() and passes the new object as argument, plot flag.
  152. # on_object_created() adds the object to the collection, plots on appropriate flag
  153. # and emits new_object_available.
  154. object_created = QtCore.pyqtSignal(object, bool, bool)
  155. # Emitted when a object has been changed (like scaled, mirrored)
  156. object_changed = QtCore.pyqtSignal(object)
  157. # Emitted after object has been plotted.
  158. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  159. object_plotted = QtCore.pyqtSignal(object)
  160. # Emitted when a new object has been added or deleted from/to the collection
  161. object_status_changed = QtCore.pyqtSignal(object, str)
  162. message = QtCore.pyqtSignal(str, str, str)
  163. # Emmited when shell command is finished(one command only)
  164. shell_command_finished = QtCore.pyqtSignal(object)
  165. # Emitted when multiprocess pool has been recreated
  166. pool_recreated = QtCore.pyqtSignal(object)
  167. # Emitted when an unhandled exception happens
  168. # in the worker task.
  169. thread_exception = QtCore.pyqtSignal(object)
  170. # used to signal that there are arguments for the app
  171. args_at_startup = QtCore.pyqtSignal(list)
  172. # a reusable signal to replot a list of objects
  173. # should be disconnected after use so it can be reused
  174. replot_signal = pyqtSignal(list)
  175. def __init__(self, user_defaults=True, post_gui=None):
  176. """
  177. Starts the application.
  178. :return: app
  179. :rtype: App
  180. """
  181. App.log.info("FlatCAM Starting...")
  182. self.main_thread = QtWidgets.QApplication.instance().thread()
  183. # ############################################################################
  184. # # ################# OS-specific ############################################
  185. # ############################################################################
  186. portable = False
  187. # Folder for user settings.
  188. if sys.platform == 'win32':
  189. # #########################################################################
  190. # Setup the listening thread for another instance launching with args #####
  191. # #########################################################################
  192. # make sure the thread is stored by using a self. otherwise it's garbage collected
  193. self.th = QtCore.QThread()
  194. self.th.start(priority=QtCore.QThread.LowestPriority)
  195. self.new_launch = ArgsThread()
  196. self.new_launch.open_signal[list].connect(self.on_startup_args)
  197. self.new_launch.moveToThread(self.th)
  198. self.new_launch.start.emit()
  199. from win32com.shell import shell, shellcon
  200. if platform.architecture()[0] == '32bit':
  201. App.log.debug("Win32!")
  202. else:
  203. App.log.debug("Win64!")
  204. # #########################################################################
  205. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  206. # #########################################################################
  207. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  208. try:
  209. with open(config_file, 'r'):
  210. pass
  211. except FileNotFoundError:
  212. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  213. try:
  214. with open(config_file, 'r') as f:
  215. try:
  216. for line in f:
  217. param = str(line).replace('\n', '').rpartition('=')
  218. if param[0] == 'portable':
  219. try:
  220. portable = eval(param[2])
  221. except NameError:
  222. portable = False
  223. if param[0] == 'headless':
  224. if param[2].lower() == 'true':
  225. self.cmd_line_headless = 1
  226. else:
  227. self.cmd_line_headless = None
  228. except Exception as e:
  229. log.debug('App.__init__() -->%s' % str(e))
  230. return
  231. except FileNotFoundError as e:
  232. log.debug(str(e))
  233. pass
  234. if portable is False:
  235. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  236. else:
  237. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  238. self.os = 'windows'
  239. else: # Linux/Unix/MacOS
  240. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  241. self.os = 'unix'
  242. # ##########################################################################
  243. # ################## Setup folders and files ###############################
  244. # ##########################################################################
  245. if not os.path.exists(self.data_path):
  246. os.makedirs(self.data_path)
  247. App.log.debug('Created data folder: ' + self.data_path)
  248. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  249. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  250. self.postprocessorpaths = os.path.join(self.data_path, 'postprocessors')
  251. if not os.path.exists(self.postprocessorpaths):
  252. os.makedirs(self.postprocessorpaths)
  253. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  254. # create current_defaults.FlatConfig file if there is none
  255. try:
  256. f = open(self.data_path + '/current_defaults.FlatConfig')
  257. f.close()
  258. except IOError:
  259. App.log.debug('Creating empty current_defaults.FlatConfig')
  260. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  261. json.dump({}, f)
  262. f.close()
  263. # create factory_defaults.FlatConfig file if there is none
  264. try:
  265. f = open(self.data_path + '/factory_defaults.FlatConfig')
  266. f.close()
  267. except IOError:
  268. App.log.debug('Creating empty factory_defaults.FlatConfig')
  269. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  270. json.dump({}, f)
  271. f.close()
  272. # create a recent files json file if there is none
  273. try:
  274. f = open(self.data_path + '/recent.json')
  275. f.close()
  276. except IOError:
  277. App.log.debug('Creating empty recent.json')
  278. f = open(self.data_path + '/recent.json', 'w')
  279. json.dump([], f)
  280. f.close()
  281. # create a recent projects json file if there is none
  282. try:
  283. fp = open(self.data_path + '/recent_projects.json')
  284. fp.close()
  285. except IOError:
  286. App.log.debug('Creating empty recent_projects.json')
  287. fp = open(self.data_path + '/recent_projects.json', 'w')
  288. json.dump([], fp)
  289. fp.close()
  290. # Application directory. CHDIR to it. Otherwise, trying to load
  291. # GUI icons will fail as their path is relative.
  292. # This will fail under cx_freeze ...
  293. self.app_home = os.path.dirname(os.path.realpath(__file__))
  294. App.log.debug("Application path is " + self.app_home)
  295. App.log.debug("Started in " + os.getcwd())
  296. # cx_freeze workaround
  297. if os.path.isfile(self.app_home):
  298. self.app_home = os.path.dirname(self.app_home)
  299. os.chdir(self.app_home)
  300. # #############################################################################
  301. # ##################### CREATE MULTIPROCESSING POOL ###########################
  302. # #############################################################################
  303. self.pool = Pool()
  304. # ##########################################################################
  305. # ################## Setting the Splash Screen #############################
  306. # ##########################################################################
  307. settings = QSettings("Open Source", "FlatCAM")
  308. if settings.contains("splash_screen"):
  309. show_splash = settings.value("splash_screen")
  310. else:
  311. settings.setValue('splash_screen', 1)
  312. # This will write the setting to the platform specific storage.
  313. del settings
  314. show_splash = 1
  315. if show_splash and self.cmd_line_headless != 1:
  316. splash_pix = QtGui.QPixmap('share/splash.png')
  317. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  318. # self.splash.setMask(splash_pix.mask())
  319. # move splashscreen to the current monitor
  320. desktop = QtWidgets.QApplication.desktop()
  321. screen = desktop.screenNumber(QtGui.QCursor.pos())
  322. current_screen_center = desktop.availableGeometry(screen).center()
  323. self.splash.move(current_screen_center - self.splash.rect().center())
  324. self.splash.show()
  325. self.splash.showMessage(_("FlatCAM is initializing ..."),
  326. alignment=Qt.AlignBottom | Qt.AlignLeft,
  327. color=QtGui.QColor("gray"))
  328. else:
  329. show_splash = 0
  330. # #############################################################################
  331. # ##################### Initialize GUI ########################################
  332. # #############################################################################
  333. # FlatCAM colors used in plotting
  334. self.FC_light_green = '#BBF268BF'
  335. self.FC_dark_green = '#006E20BF'
  336. self.FC_light_blue = '#a5a5ffbf'
  337. self.FC_dark_blue = '#0000ffbf'
  338. QtCore.QObject.__init__(self)
  339. self.ui = FlatCAMGUI(self.version, self.beta, self)
  340. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  341. self.ui.final_save.connect(self.final_save)
  342. # #############################################################################
  343. # ############################## Data #########################################
  344. # #############################################################################
  345. self.recent = []
  346. self.recent_projects = []
  347. self.clipboard = QtWidgets.QApplication.clipboard()
  348. self.project_filename = None
  349. self.toggle_units_ignore = False
  350. # self.defaults_form = PreferencesUI()
  351. # when adding entries here read the comments in the method found bellow named:
  352. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  353. self.defaults_form_fields = {
  354. # General App
  355. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  356. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  357. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  358. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  359. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  360. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  361. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  362. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  363. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  364. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  365. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  366. "global_open_style": self.ui.general_defaults_form.general_app_group.open_style_cb,
  367. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  368. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  369. # General GUI Preferences
  370. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  371. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  372. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  373. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  374. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  375. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  376. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  377. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  378. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  379. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  380. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  381. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  382. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  383. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  384. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  385. "global_activity_icon": self.ui.general_defaults_form.general_gui_group.activity_combo,
  386. # General GUI Settings
  387. "global_layout": self.ui.general_defaults_form.general_gui_set_group.layout_combo,
  388. "global_hover": self.ui.general_defaults_form.general_gui_set_group.hover_cb,
  389. "global_selection_shape": self.ui.general_defaults_form.general_gui_set_group.selection_cb,
  390. "global_systray_icon": self.ui.general_defaults_form.general_gui_set_group.systray_cb,
  391. "global_shell_at_startup": self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb,
  392. "global_project_at_startup": self.ui.general_defaults_form.general_gui_set_group.project_startup_cb,
  393. "global_project_autohide": self.ui.general_defaults_form.general_gui_set_group.project_autohide_cb,
  394. "global_toggle_tooltips": self.ui.general_defaults_form.general_gui_set_group.toggle_tooltips_cb,
  395. "global_delete_confirmation": self.ui.general_defaults_form.general_gui_set_group.delete_conf_cb,
  396. # Gerber General
  397. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  398. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  399. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  400. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  401. # Gerber Options
  402. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  403. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  404. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  405. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  406. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  407. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  408. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  409. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  410. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  411. # Gerber Advanced Options
  412. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  413. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  414. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  415. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  416. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  417. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  418. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  419. # Gerber Export
  420. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  421. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  422. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  423. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  424. # Gerber Editor
  425. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  426. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  427. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  428. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  429. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  430. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  431. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  432. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  433. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  434. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  435. "gerber_editor_circ_angle":
  436. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  437. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  438. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  439. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  440. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  441. # Excellon General
  442. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  443. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  444. "excellon_format_upper_in":
  445. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  446. "excellon_format_lower_in":
  447. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  448. "excellon_format_upper_mm":
  449. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  450. "excellon_format_lower_mm":
  451. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  452. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  453. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  454. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  455. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  456. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  457. # Excellon Options
  458. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  459. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  460. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  461. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  462. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  463. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  464. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  465. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  466. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  467. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  468. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  469. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  470. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  471. # Excellon Advanced Options
  472. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  473. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  474. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  475. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  476. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  477. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  478. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  479. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  480. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  481. # Excellon Export
  482. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  483. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  484. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  485. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  486. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  487. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  488. # Excellon Editor
  489. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  490. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  491. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  492. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  493. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  494. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  495. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  496. "excellon_editor_circ_angle":
  497. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  498. # Excellon Slots
  499. "excellon_editor_slot_direction":
  500. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  501. "excellon_editor_slot_angle":
  502. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  503. "excellon_editor_slot_length":
  504. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  505. # Excellon Slots
  506. "excellon_editor_slot_array_size":
  507. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  508. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  509. "excellon_editor_slot_lin_pitch":
  510. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  511. "excellon_editor_slot_lin_angle":
  512. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  513. "excellon_editor_slot_circ_dir":
  514. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  515. "excellon_editor_slot_circ_angle":
  516. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  517. # Geometry General
  518. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  519. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  520. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  521. # Geometry Options
  522. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  523. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  524. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  525. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  526. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  527. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  528. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  529. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  530. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  531. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  532. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  533. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  534. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  535. # Geometry Advanced Options
  536. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  537. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  538. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  539. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  540. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  541. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  542. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  543. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  544. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  545. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  546. # Geometry Editor
  547. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  548. # CNCJob General
  549. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  550. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  551. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  552. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  553. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  554. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  555. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  556. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  557. # CNC Job Options
  558. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  559. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  560. # CNC Job Advanced Options
  561. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  562. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  563. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  564. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  565. # NCC Tool
  566. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  567. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  568. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  569. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  570. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  571. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  572. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  573. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  574. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  575. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  576. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  577. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  578. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  579. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  580. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  581. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  582. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  583. # CutOut Tool
  584. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  585. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  586. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  587. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  588. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  589. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  590. # Paint Area Tool
  591. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  592. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  593. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  594. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  595. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  596. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  597. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  598. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  599. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  600. # 2-sided Tool
  601. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  602. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  603. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  604. # Film Tool
  605. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  606. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  607. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  608. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  609. # Panelize Tool
  610. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  611. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  612. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  613. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  614. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  615. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  616. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  617. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  618. # Calculators Tool
  619. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  620. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  621. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  622. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  623. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  624. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  625. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  626. # Transformations Tool
  627. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  628. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  629. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  630. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  631. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  632. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  633. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  634. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  635. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  636. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  637. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  638. # SolderPaste Dispensing Tool
  639. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  640. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  641. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  642. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  643. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  644. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  645. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  646. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  647. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  648. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  649. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  650. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  651. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  652. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  653. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  654. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  655. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  656. # Utilities
  657. # File associations
  658. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  659. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  660. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  661. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  662. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  663. }
  664. # ############################
  665. # ### LOAD POSTPROCESSORS ####
  666. # ############################
  667. self.postprocessors = load_postprocessors(self)
  668. for name in list(self.postprocessors.keys()):
  669. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  670. if name.partition('_')[0] == 'Paste':
  671. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  672. continue
  673. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  674. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  675. if name == 'hpgl':
  676. continue
  677. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  678. # ############################
  679. # ### LOAD LANGUAGES ####
  680. # ############################
  681. self.languages = fcTranslate.load_languages()
  682. for name in sorted(self.languages.values()):
  683. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  684. # #################################################################################
  685. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  686. # #################################################################################
  687. self.defaults = LoudDict()
  688. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  689. self.defaults.update({
  690. # Global APP Preferences
  691. "first_run": True,
  692. "units": "IN",
  693. "global_serial": 0,
  694. "global_stats": {},
  695. "global_tabs_detachable": True,
  696. "global_graphic_engine": '3D',
  697. "global_app_level": 'b',
  698. "global_portable": False,
  699. "global_language": 'English',
  700. "global_version_check": True,
  701. "global_send_stats": True,
  702. "global_pan_button": '2',
  703. "global_mselect_key": 'Control',
  704. "global_project_at_startup": False,
  705. "global_systray_icon": True,
  706. "global_project_autohide": True,
  707. "global_toggle_tooltips": True,
  708. "global_worker_number": 2,
  709. "global_tolerance": 0.005,
  710. "global_open_style": True,
  711. "global_delete_confirmation": True,
  712. "global_compression_level": 3,
  713. "global_save_compressed": True,
  714. # Global GUI Preferences
  715. "global_gridx": 0.0393701,
  716. "global_gridy": 0.0393701,
  717. "global_snap_max": 0.001968504,
  718. "global_workspace": False,
  719. "global_workspaceT": "A4P",
  720. "global_grid_context_menu": {
  721. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  722. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  723. },
  724. "global_plot_fill": '#BBF268BF',
  725. "global_plot_line": '#006E20BF',
  726. "global_sel_fill": '#a5a5ffbf',
  727. "global_sel_line": '#0000ffbf',
  728. "global_alt_sel_fill": '#BBF268BF',
  729. "global_alt_sel_line": '#006E20BF',
  730. "global_draw_color": '#FF0000',
  731. "global_sel_draw_color": '#0000FF',
  732. "global_proj_item_color": '#000000',
  733. "global_proj_item_dis_color": '#b7b7cb',
  734. "global_activity_icon": 'Ball green',
  735. "global_toolbar_view": 511,
  736. "global_background_timeout": 300000, # Default value is 5 minutes
  737. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  738. # (python trace only for unknown errors),
  739. # 1 = show trace(show trace always),
  740. # 2 = (For the future).
  741. # Persistence
  742. "global_last_folder": None,
  743. "global_last_save_folder": None,
  744. # Default window geometry
  745. "global_def_win_x": 100,
  746. "global_def_win_y": 100,
  747. "global_def_win_w": 1024,
  748. "global_def_win_h": 650,
  749. "global_def_notebook_width": 1,
  750. # Constants...
  751. "global_defaults_save_period_ms": 20000, # Time between default saves.
  752. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  753. "global_shell_at_startup": False, # Show the shell at startup.
  754. "global_recent_limit": 10, # Max. items in recent list.
  755. "fit_key": 'V',
  756. "zoom_out_key": '-',
  757. "zoom_in_key": '=',
  758. "grid_toggle_key": 'G',
  759. "global_zoom_ratio": 1.5,
  760. "global_point_clipboard_format": "(%.4f, %.4f)",
  761. "global_zdownrate": None,
  762. # General GUI Settings
  763. "global_hover": False,
  764. "global_selection_shape": True,
  765. "global_layout": "compact",
  766. # Gerber General
  767. "gerber_plot": True,
  768. "gerber_solid": True,
  769. "gerber_multicolored": False,
  770. "gerber_circle_steps": 128,
  771. "gerber_use_buffer_for_union": True,
  772. # Gerber Options
  773. "gerber_isotooldia": 0.00787402,
  774. "gerber_isopasses": 1,
  775. "gerber_isooverlap": 0.00393701,
  776. "gerber_milling_type": "cl",
  777. "gerber_combine_passes": False,
  778. "gerber_noncoppermargin": 0.00393701,
  779. "gerber_noncopperrounded": False,
  780. "gerber_bboxmargin": 0.00393701,
  781. "gerber_bboxrounded": False,
  782. # Gerber Advanced Options
  783. "gerber_aperture_display": False,
  784. "gerber_aperture_scale_factor": 1.0,
  785. "gerber_aperture_buffer_factor": 0.0,
  786. "gerber_follow": False,
  787. "gerber_buffering": "full",
  788. "gerber_simplification": False,
  789. "gerber_simp_tolerance": 0.0005,
  790. # Gerber Export
  791. "gerber_exp_units": 'IN',
  792. "gerber_exp_integer": 2,
  793. "gerber_exp_decimals": 4,
  794. "gerber_exp_zeros": 'L',
  795. # Gerber Editor
  796. "gerber_editor_sel_limit": 30,
  797. "gerber_editor_newcode": 10,
  798. "gerber_editor_newsize": 0.8,
  799. "gerber_editor_newtype": 'C',
  800. "gerber_editor_newdim": "0.5, 0.5",
  801. "gerber_editor_array_size": 5,
  802. "gerber_editor_lin_axis": 'X',
  803. "gerber_editor_lin_pitch": 1,
  804. "gerber_editor_lin_angle": 0.0,
  805. "gerber_editor_circ_dir": 'CW',
  806. "gerber_editor_circ_angle": 0.0,
  807. "gerber_editor_scale_f": 1.0,
  808. "gerber_editor_buff_f": 0.1,
  809. "gerber_editor_ma_low": 0.0,
  810. "gerber_editor_ma_high": 1.0,
  811. # Excellon General
  812. "excellon_plot": True,
  813. "excellon_solid": True,
  814. "excellon_format_upper_in": 2,
  815. "excellon_format_lower_in": 4,
  816. "excellon_format_upper_mm": 3,
  817. "excellon_format_lower_mm": 3,
  818. "excellon_zeros": "L",
  819. "excellon_units": "INCH",
  820. "excellon_update": True,
  821. "excellon_optimization_type": 'B',
  822. "excellon_search_time": 3,
  823. # Excellon Options
  824. "excellon_drillz": -0.0590551,
  825. "excellon_travelz": 0.0787402,
  826. "excellon_endz": 0.5,
  827. "excellon_feedrate": 3.14961,
  828. "excellon_spindlespeed": None,
  829. "excellon_dwell": False,
  830. "excellon_dwelltime": 1,
  831. "excellon_toolchange": False,
  832. "excellon_toolchangez": 0.5,
  833. "excellon_ppname_e": 'default',
  834. "excellon_tooldia": 0.0314961,
  835. "excellon_slot_tooldia": 0.0708661,
  836. "excellon_gcode_type": "drills",
  837. # Excellon Advanced Options
  838. "excellon_offset": 0.0,
  839. "excellon_toolchangexy": "0.0, 0.0",
  840. "excellon_startz": None,
  841. "excellon_feedrate_rapid": 31.4961,
  842. "excellon_z_pdepth": -0.02,
  843. "excellon_feedrate_probe": 3.14961,
  844. "excellon_spindledir": 'CW',
  845. "excellon_f_plunge": False,
  846. "excellon_f_retract": False,
  847. # Excellon Export
  848. "excellon_exp_units": 'INCH',
  849. "excellon_exp_format": 'ndec',
  850. "excellon_exp_integer": 2,
  851. "excellon_exp_decimals": 4,
  852. "excellon_exp_zeros": 'LZ',
  853. "excellon_exp_slot_type": 'routing',
  854. # Excellon Editor
  855. "excellon_editor_sel_limit": 30,
  856. "excellon_editor_newdia": 0.039,
  857. "excellon_editor_array_size": 5,
  858. "excellon_editor_lin_dir": 'X',
  859. "excellon_editor_lin_pitch": 0.1,
  860. "excellon_editor_lin_angle": 0.0,
  861. "excellon_editor_circ_dir": 'CW',
  862. "excellon_editor_circ_angle": 12,
  863. # Excellon Slots
  864. "excellon_editor_slot_direction": 'X',
  865. "excellon_editor_slot_angle": 0.0,
  866. "excellon_editor_slot_length": 5.0,
  867. # Excellon Slot Array
  868. "excellon_editor_slot_array_size": 5,
  869. "excellon_editor_slot_lin_dir": 'X',
  870. "excellon_editor_slot_lin_pitch": 0.1,
  871. "excellon_editor_slot_lin_angle": 0.0,
  872. "excellon_editor_slot_circ_dir": 'CW',
  873. "excellon_editor_slot_circ_angle": 0.0,
  874. # Geometry General
  875. "geometry_plot": True,
  876. "geometry_circle_steps": 128,
  877. "geometry_cnctooldia": "0.0944882",
  878. # Geometry Options
  879. "geometry_cutz": -0.0944882,
  880. "geometry_vtipdia": 0.1,
  881. "geometry_vtipangle": 30,
  882. "geometry_multidepth": False,
  883. "geometry_depthperpass": 0.0314961,
  884. "geometry_travelz": 0.0787402,
  885. "geometry_toolchange": False,
  886. "geometry_toolchangez": 0.5,
  887. "geometry_endz": 0.5,
  888. "geometry_feedrate": 3.14961,
  889. "geometry_feedrate_z": 3.14961,
  890. "geometry_spindlespeed": None,
  891. "geometry_dwell": False,
  892. "geometry_dwelltime": 1,
  893. "geometry_ppname_g": 'default',
  894. # Geometry Advanced Options
  895. "geometry_toolchangexy": "0.0, 0.0",
  896. "geometry_startz": None,
  897. "geometry_feedrate_rapid": 3.14961,
  898. "geometry_extracut": False,
  899. "geometry_z_pdepth": -0.02,
  900. "geometry_f_plunge": False,
  901. "geometry_spindledir": 'CW',
  902. "geometry_feedrate_probe": 3.14961,
  903. "geometry_segx": 0.0,
  904. "geometry_segy": 0.0,
  905. # Geometry Editor
  906. "geometry_editor_sel_limit": 30,
  907. # CNC Job General
  908. "cncjob_plot": True,
  909. "cncjob_plot_kind": 'all',
  910. "cncjob_annotation": True,
  911. "cncjob_tooldia": 0.0393701,
  912. "cncjob_coords_type": "G90",
  913. "cncjob_coords_decimals": 4,
  914. "cncjob_fr_decimals": 2,
  915. "cncjob_steps_per_circle": 128,
  916. # CNC Job Options
  917. "cncjob_prepend": "",
  918. "cncjob_append": "",
  919. # CNC Job Advanced Options
  920. "cncjob_toolchange_macro": "",
  921. "cncjob_toolchange_macro_enable": False,
  922. "cncjob_annotation_fontsize": 9,
  923. "cncjob_annotation_fontcolor": '#990000',
  924. # NCC Tool
  925. "tools_ncctools": "0.0393701, 0.019685",
  926. "tools_nccorder": 'rev',
  927. "tools_nccoverlap": 0.015748,
  928. "tools_nccmargin": 0.0393701,
  929. "tools_nccmethod": "seed",
  930. "tools_nccconnect": True,
  931. "tools_ncccontour": True,
  932. "tools_nccrest": False,
  933. "tools_ncc_offset_choice": False,
  934. "tools_ncc_offset_value": 0.0000,
  935. "tools_nccref": 'itself',
  936. "tools_ncc_plotting": 'normal',
  937. "tools_nccmilling_type": 'cl',
  938. "tools_ncctool_type": 'V',
  939. "tools_ncccutz": -0.001968504,
  940. "tools_ncctipdia": 0.00393701,
  941. "tools_ncctipangle": 30,
  942. # Cutout Tool
  943. "tools_cutouttooldia": 0.0944882,
  944. "tools_cutoutkind": "single",
  945. "tools_cutoutmargin": 0.00393701,
  946. "tools_cutoutgapsize": 0.15748,
  947. "tools_gaps_ff": "4",
  948. "tools_cutout_convexshape": False,
  949. # Paint Tool
  950. "tools_painttooldia": 0.023622,
  951. "tools_paintorder": 'rev',
  952. "tools_paintoverlap": 0.015748,
  953. "tools_paintmargin": 0.0,
  954. "tools_paintmethod": "seed",
  955. "tools_selectmethod": "all",
  956. "tools_pathconnect": True,
  957. "tools_paintcontour": True,
  958. "tools_paint_plotting": 'normal',
  959. # 2-Sided Tool
  960. "tools_2sided_mirror_axis": "X",
  961. "tools_2sided_axis_loc": "point",
  962. "tools_2sided_drilldia": 0.11811,
  963. # Film Tool
  964. "tools_film_type": 'neg',
  965. "tools_film_boundary": 0.0393701,
  966. "tools_film_scale": 0,
  967. "tools_film_color": '#000000',
  968. # Panel Tool
  969. "tools_panelize_spacing_columns": 0,
  970. "tools_panelize_spacing_rows": 0,
  971. "tools_panelize_columns": 1,
  972. "tools_panelize_rows": 1,
  973. "tools_panelize_constrain": False,
  974. "tools_panelize_constrainx": 0.0,
  975. "tools_panelize_constrainy": 0.0,
  976. "tools_panelize_panel_type": 'gerber',
  977. # Calculators Tool
  978. "tools_calc_vshape_tip_dia": 0.007874,
  979. "tools_calc_vshape_tip_angle": 30,
  980. "tools_calc_vshape_cut_z": 0.000787,
  981. "tools_calc_electro_length": 10.0,
  982. "tools_calc_electro_width": 10.0,
  983. "tools_calc_electro_cdensity": 13.0,
  984. "tools_calc_electro_growth": 10.0,
  985. # Transform Tool
  986. "tools_transform_rotate": 90,
  987. "tools_transform_skew_x": 0.0,
  988. "tools_transform_skew_y": 0.0,
  989. "tools_transform_scale_x": 1.0,
  990. "tools_transform_scale_y": 1.0,
  991. "tools_transform_scale_link": True,
  992. "tools_transform_scale_reference": True,
  993. "tools_transform_offset_x": 0.0,
  994. "tools_transform_offset_y": 0.0,
  995. "tools_transform_mirror_reference": False,
  996. "tools_transform_mirror_point": (0, 0),
  997. # SolderPaste Tool
  998. "tools_solderpaste_tools": "0.0393701, 0.011811",
  999. "tools_solderpaste_new": 0.011811,
  1000. "tools_solderpaste_z_start": 0.00019685039,
  1001. "tools_solderpaste_z_dispense": 0.00393701,
  1002. "tools_solderpaste_z_stop": 0.00019685039,
  1003. "tools_solderpaste_z_travel": 0.00393701,
  1004. "tools_solderpaste_z_toolchange": 0.0393701,
  1005. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  1006. "tools_solderpaste_frxy": 3.0,
  1007. "tools_solderpaste_frz": 3.0,
  1008. "tools_solderpaste_frz_dispense": 0.0393701,
  1009. "tools_solderpaste_speedfwd": 20,
  1010. "tools_solderpaste_dwellfwd": 1,
  1011. "tools_solderpaste_speedrev": 10,
  1012. "tools_solderpaste_dwellrev": 1,
  1013. "tools_solderpaste_pp": 'Paste_1',
  1014. # Subtract Tool
  1015. "tools_sub_close_paths": True,
  1016. # Utilities
  1017. # file associations
  1018. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  1019. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  1020. 'ncg, ncp, out, plt, ply, rol, sbp, tap, xpi',
  1021. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, g4, gb0, gb1, gb2, gb3, gb5, gb6, gb7, gb8, gb9, gbd, '
  1022. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  1023. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  1024. # Keyword list
  1025. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  1026. 'Repetier, Roland_MDX_20, Toolchange_Custom, Toolchange_Probe_MACH3, '
  1027. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, axisoffset, box, '
  1028. 'center_x, center_y, columns, combine, connect, contour, default, '
  1029. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwell, dwelltime, '
  1030. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  1031. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  1032. 'minoffset, multidepth, name, offset, opt_type, order, outname, overlap, '
  1033. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  1034. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  1035. 'toolchange_xy, use_threads, value, x, x0, x1, y, y0, y1, z_cut, z_move'
  1036. ,
  1037. })
  1038. # ############################################################
  1039. # ############### Load defaults from file ####################
  1040. # ############################################################
  1041. if user_defaults:
  1042. self.load_defaults(filename='current_defaults')
  1043. # #############################################################
  1044. # ############## APPLY APP LANGUAGE ###########################
  1045. # #############################################################
  1046. ret_val = fcTranslate.apply_language('strings')
  1047. if ret_val == "no language":
  1048. self.inform.emit('[ERROR] %s' %
  1049. _("Could not find the Language files. The App strings are missing."))
  1050. log.debug("Could not find the Language files. The App strings are missing.")
  1051. else:
  1052. # make the current language the current selection on the language combobox
  1053. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1054. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1055. # ##############################################################
  1056. # ################# CREATE UNIQUE SERIAL NUMBER ################
  1057. # ##############################################################
  1058. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1059. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1060. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  1061. self.save_defaults(silent=True, first_time=True)
  1062. self.propagate_defaults(silent=True)
  1063. self.restore_main_win_geom()
  1064. # def auto_save_defaults():
  1065. # try:
  1066. # self.save_defaults(silent=True)
  1067. # self.propagate_defaults(silent=True)
  1068. # finally:
  1069. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1070. # the following lines activates automatic defaults save
  1071. # if user_defaults:
  1072. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1073. # self.options_form = PreferencesUI()
  1074. self.options_form_fields = {
  1075. "units": self.ui.general_options_form.general_app_group.units_radio,
  1076. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  1077. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  1078. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  1079. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  1080. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  1081. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  1082. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  1083. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  1084. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  1085. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  1086. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  1087. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  1088. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  1089. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  1090. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  1091. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  1092. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  1093. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  1094. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1095. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1096. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  1097. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  1098. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  1099. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  1100. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  1101. "excellon_endz": self.ui.excellon_options_form.excellon_opt_group.eendz_entry,
  1102. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  1103. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  1104. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  1105. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  1106. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  1107. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  1108. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  1109. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  1110. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1111. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  1112. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  1113. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  1114. "excellon_spindledir": self.ui.excellon_options_form.excellon_adv_opt_group.spindledir_radio,
  1115. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  1116. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  1117. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  1118. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  1119. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  1120. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  1121. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  1122. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  1123. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  1124. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  1125. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  1126. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  1127. "geometry_endz": self.ui.geometry_options_form.geometry_opt_group.gendz_entry,
  1128. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  1129. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  1130. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  1131. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  1132. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1133. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  1134. "geometry_spindledir": self.ui.geometry_options_form.geometry_adv_opt_group.spindledir_radio,
  1135. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  1136. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  1137. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  1138. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  1139. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  1140. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  1141. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  1142. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  1143. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  1144. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  1145. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  1146. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  1147. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  1148. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  1149. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  1150. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  1151. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  1152. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  1153. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  1154. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  1155. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  1156. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  1157. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  1158. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  1159. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  1160. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  1161. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  1162. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  1163. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  1164. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  1165. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  1166. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  1167. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  1168. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  1169. }
  1170. for name in list(self.postprocessors.keys()):
  1171. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1172. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1173. self.options = LoudDict()
  1174. self.options.set_change_callback(self.on_options_dict_change)
  1175. self.options.update({
  1176. "units": "IN",
  1177. "global_gridx": 1.0,
  1178. "global_gridy": 1.0,
  1179. "global_snap_max": 0.05,
  1180. "global_background_timeout": 300000, # Default value is 5 minutes
  1181. "global_verbose_error_level": 0, # Shell verbosity:
  1182. # 0 = default(python trace only for unknown errors),
  1183. # 1 = show trace(show trace allways), 2 = (For the future).
  1184. "gerber_plot": True,
  1185. "gerber_solid": True,
  1186. "gerber_multicolored": False,
  1187. "gerber_isotooldia": 0.016,
  1188. "gerber_isopasses": 1,
  1189. "gerber_isooverlap": 0.15,
  1190. "gerber_combine_passes": True,
  1191. "gerber_noncoppermargin": 0.0,
  1192. "gerber_noncopperrounded": False,
  1193. "gerber_bboxmargin": 0.0,
  1194. "gerber_bboxrounded": False,
  1195. "excellon_plot": True,
  1196. "excellon_solid": False,
  1197. "excellon_format_upper_in": 2,
  1198. "excellon_format_lower_in": 4,
  1199. "excellon_format_upper_mm": 3,
  1200. "excellon_format_lower_mm": 3,
  1201. "excellon_units": 'INCH',
  1202. "excellon_optimization_type": 'B',
  1203. "excellon_search_time": 3,
  1204. "excellon_zeros": "L",
  1205. "excellon_drillz": -0.1,
  1206. "excellon_travelz": 0.1,
  1207. "excellon_feedrate": 3.0,
  1208. "excellon_feedrate_rapid": 3.0,
  1209. "excellon_spindlespeed": None,
  1210. "excellon_spindledir": 'CW',
  1211. "excellon_dwell": True,
  1212. "excellon_dwelltime": 1000,
  1213. "excellon_toolchange": False,
  1214. "excellon_toolchangez": 1.0,
  1215. "excellon_toolchangexy": "0.0, 0.0",
  1216. "excellon_tooldia": 0.016,
  1217. "excellon_ppname_e": 'default',
  1218. "excellon_f_plunge": False,
  1219. "excellon_startz": None,
  1220. "excellon_endz": 2.0,
  1221. "geometry_plot": True,
  1222. "geometry_segx": 0.0,
  1223. "geometry_segy": 0.0,
  1224. "geometry_cutz": -0.002,
  1225. "geometry_vtipdia": 0.1,
  1226. "geometry_vtipangle": 30,
  1227. "geometry_travelz": 0.1,
  1228. "geometry_feedrate": 3.0,
  1229. "geometry_feedrate_z": 3.0,
  1230. "geometry_feedrate_rapid": 3.0,
  1231. "geometry_spindlespeed": None,
  1232. "geometry_spindledir": 'CW',
  1233. "geometry_dwell": True,
  1234. "geometry_dwelltime": 1000,
  1235. "geometry_cnctooldia": 0.016,
  1236. "geometry_toolchange": False,
  1237. "geometry_toolchangez": 2.0,
  1238. "geometry_toolchangexy": "0.0, 0.0",
  1239. "geometry_startz": None,
  1240. "geometry_endz": 2.0,
  1241. "geometry_ppname_g": "default",
  1242. "geometry_f_plunge": False,
  1243. "geometry_depthperpass": 0.002,
  1244. "geometry_multidepth": False,
  1245. "geometry_extracut": False,
  1246. "cncjob_plot": True,
  1247. "cncjob_tooldia": 0.016,
  1248. "cncjob_prepend": "",
  1249. "cncjob_append": "",
  1250. "tools_ncctools": "1.0, 0.5",
  1251. "tools_nccoverlap": 0.4,
  1252. "tools_nccmargin": 1,
  1253. "tools_cutouttooldia": 0.07,
  1254. "tools_cutoutmargin": 0.1,
  1255. "tools_cutoutgapsize": 0.15,
  1256. "tools_gaps_ff": "8",
  1257. "tools_painttooldia": 0.07,
  1258. "tools_paintoverlap": 0.15,
  1259. "tools_paintmargin": 0.0,
  1260. "tools_paintmethod": "seed",
  1261. "tools_selectmethod": "single",
  1262. "tools_pathconnect": True,
  1263. "tools_paintcontour": True,
  1264. "tools_2sided_mirror_axis": "X",
  1265. "tools_2sided_axis_loc": 'point',
  1266. "tools_2sided_drilldia": 1,
  1267. "tools_film_type": 'neg',
  1268. "tools_film_boundary": 1,
  1269. "tools_film_scale": 0,
  1270. "tools_panelize_spacing_columns": 0,
  1271. "tools_panelize_spacing_rows": 0,
  1272. "tools_panelize_columns": 1,
  1273. "tools_panelize_rows": 1,
  1274. "tools_panelize_constrain": False,
  1275. "tools_panelize_constrainx": 0.0,
  1276. "tools_panelize_constrainy": 0.0
  1277. })
  1278. self.options.update(self.defaults) # Copy app defaults to project options
  1279. self.gen_form = None
  1280. self.ger_form = None
  1281. self.exc_form = None
  1282. self.geo_form = None
  1283. self.cnc_form = None
  1284. self.tools_form = None
  1285. self.fa_form = None
  1286. self.on_options_combo_change(0) # Will show the initial form
  1287. # ################################
  1288. # ### Initialize the color box's color in Preferences -> Global -> Color
  1289. # Init Plot Colors
  1290. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  1291. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  1292. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  1293. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  1294. int(self.defaults['global_plot_fill'][7:9], 16))
  1295. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  1296. int(self.defaults['global_plot_fill'][7:9], 16))
  1297. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  1298. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  1299. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  1300. # Init Left-Right Selection colors
  1301. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  1302. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  1303. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  1304. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  1305. int(self.defaults['global_sel_fill'][7:9], 16))
  1306. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  1307. int(self.defaults['global_sel_fill'][7:9], 16))
  1308. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  1309. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  1310. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  1311. # Init Right-Left Selection colors
  1312. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  1313. self.defaults['global_alt_sel_fill'])
  1314. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  1315. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  1316. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  1317. int(self.defaults['global_sel_fill'][7:9], 16))
  1318. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  1319. int(self.defaults['global_sel_fill'][7:9], 16))
  1320. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  1321. self.defaults['global_alt_sel_line'])
  1322. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  1323. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  1324. # Init Draw color and Selection Draw Color
  1325. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  1326. self.defaults['global_draw_color'])
  1327. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  1328. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  1329. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  1330. self.defaults['global_sel_draw_color'])
  1331. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  1332. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  1333. # Init Project Items color
  1334. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  1335. self.defaults['global_proj_item_color'])
  1336. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  1337. "background-color:%s" % str(self.defaults['global_proj_item_color'])[:7])
  1338. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  1339. self.defaults['global_proj_item_dis_color'])
  1340. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  1341. "background-color:%s" % str(self.defaults['global_proj_item_dis_color'])[:7])
  1342. # Init the Annotation CNC Job color
  1343. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  1344. self.defaults['cncjob_annotation_fontcolor'])
  1345. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  1346. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  1347. # Init the Tool Film color
  1348. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  1349. self.defaults['tools_film_color'])
  1350. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  1351. "background-color:%s" % str(self.defaults['tools_film_color'])[:7])
  1352. # ### End of Data ####
  1353. # ###############################################
  1354. # ############# SETUP Plot Area #################
  1355. # ###############################################
  1356. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1357. if self.defaults["global_graphic_engine"] == '3D':
  1358. self.is_legacy = False
  1359. else:
  1360. self.is_legacy = True
  1361. if show_splash:
  1362. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1363. "Canvas initialization started."),
  1364. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1365. color=QtGui.QColor("gray"))
  1366. start_plot_time = time.time() # debug
  1367. self.plotcanvas = None
  1368. self.app_cursor = None
  1369. self.hover_shapes = None
  1370. self.on_plotcanvas_setup()
  1371. end_plot_time = time.time()
  1372. self.used_time = end_plot_time - start_plot_time
  1373. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1374. if show_splash:
  1375. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1376. "Canvas initialization started.\n"
  1377. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1378. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1379. color=QtGui.QColor("gray"))
  1380. self.ui.splitter.setStretchFactor(1, 2)
  1381. # #################################################################
  1382. # ####################### SYS TRAY ################################
  1383. # #################################################################
  1384. if self.defaults["global_systray_icon"]:
  1385. self.parent_w = QtWidgets.QWidget()
  1386. if self.cmd_line_headless == 1:
  1387. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1388. headless=True,
  1389. parent=self.parent_w)
  1390. else:
  1391. self.trayIcon = FlatCAMSystemTray(app=self, icon=QtGui.QIcon('share/flatcam_icon32_green.png'),
  1392. parent=self.parent_w)
  1393. # ##############################################
  1394. # ######### SETUP OBJECT COLLECTION ############
  1395. # ##############################################
  1396. self.collection = ObjectCollection(self)
  1397. self.ui.project_tab_layout.addWidget(self.collection.view)
  1398. # ### Adjust tabs width ## ##
  1399. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1400. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1401. self.collection.view.setMinimumWidth(290)
  1402. self.log.debug("Finished creating Object Collection.")
  1403. # ###############################################
  1404. # ############# Worker SETUP ####################
  1405. # ###############################################
  1406. if self.defaults["global_worker_number"]:
  1407. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1408. else:
  1409. self.workers = WorkerStack(workers_number=2)
  1410. self.worker_task.connect(self.workers.add_task)
  1411. self.log.debug("Finished creating Workers crew.")
  1412. # ################################################
  1413. # ############### Activity Monitor ###############
  1414. # ################################################
  1415. if self.defaults["global_activity_icon"] == "Ball green":
  1416. icon = 'share/active_2_static.png'
  1417. movie = "share/active_2.gif"
  1418. elif self.defaults["global_activity_icon"] == "Ball black":
  1419. icon = 'share/active_static.png'
  1420. movie = "share/active.gif"
  1421. elif self.defaults["global_activity_icon"] == "Arrow green":
  1422. icon = 'share/active_3_static.png'
  1423. movie = "share/active_3.gif"
  1424. elif self.defaults["global_activity_icon"] == "Eclipse green":
  1425. icon = 'share/active_4_static.png'
  1426. movie = "share/active_4.gif"
  1427. else:
  1428. icon = 'share/active_static.png'
  1429. movie = "share/active.gif"
  1430. self.activity_view = FlatCAMActivityView(icon=icon, movie=movie)
  1431. self.ui.infobar.addWidget(self.activity_view)
  1432. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1433. # ################################################
  1434. # ############### Signal handling ################
  1435. # ################################################
  1436. # ############# Custom signals ##################
  1437. # signal for displaying messages in status bar
  1438. self.inform.connect(self.info)
  1439. # signal to be called when the app is quiting
  1440. self.app_quit.connect(self.quit_application)
  1441. self.message.connect(self.message_dialog)
  1442. self.progress.connect(self.set_progress_bar)
  1443. # signals that are emitted when object state changes
  1444. self.object_created.connect(self.on_object_created)
  1445. self.object_changed.connect(self.on_object_changed)
  1446. self.object_plotted.connect(self.on_object_plotted)
  1447. self.plots_updated.connect(self.on_plots_updated)
  1448. # signals emitted when file state change
  1449. self.file_opened.connect(self.register_recent)
  1450. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1451. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1452. # ############# Standard signals ###################
  1453. # ### Menu
  1454. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1455. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1456. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1457. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1458. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1459. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1460. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1461. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1462. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1463. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1464. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1465. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1466. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1467. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1468. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1469. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1470. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1471. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1472. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1473. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1474. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1475. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1476. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1477. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1478. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1479. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1480. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1481. self.ui.menufile_exit.triggered.connect(self.final_save)
  1482. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1483. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1484. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1485. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1486. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1487. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1488. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1489. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1490. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1491. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1492. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1493. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1494. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1495. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1496. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1497. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1498. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1499. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1500. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1501. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1502. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1503. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1504. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1505. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1506. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1507. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1508. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1509. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1510. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1511. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1512. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1513. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1514. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1515. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1516. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1517. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1518. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1519. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1520. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1521. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1522. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1523. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1524. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1525. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1526. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1527. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1528. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1529. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1530. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1531. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1532. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1533. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1534. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1535. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1536. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1537. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1538. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1539. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1540. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1541. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1542. # ToolBar signals
  1543. self.connect_toolbar_signals()
  1544. # Notebook signals
  1545. # make the right click on the notebook tab connect to a function
  1546. self.ui.notebook.setupContextMenu()
  1547. self.ui.notebook.addContextMenu(
  1548. _("Detachable Tabs"), self.on_notebook_tab_rmb_click,
  1549. initial_checked=self.defaults["global_tabs_detachable"])
  1550. # activate initial state
  1551. self.on_notebook_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1552. # Context Menu
  1553. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1554. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1555. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1556. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1557. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1558. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1559. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1560. self.ui.clearplot.triggered.connect(self.clear_plots)
  1561. self.ui.replot.triggered.connect(self.plot_all)
  1562. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1563. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1564. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1565. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1566. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1567. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1568. # Preferences Plot Area TAB
  1569. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1570. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1571. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1572. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1573. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1574. # ##############################
  1575. # ### GUI PREFERENCES SIGNALS ##
  1576. # ##############################
  1577. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1578. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(
  1579. lambda: fcTranslate.on_language_apply_click(self, restart=True)
  1580. )
  1581. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1582. lambda: self.on_toggle_units(no_pref=False))
  1583. # ###############################################################
  1584. # ################### GUI COLORS SIGNALS ########################
  1585. # ###############################################################
  1586. # Setting plot colors signals
  1587. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(
  1588. self.on_pf_color_entry)
  1589. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(
  1590. self.on_pf_color_button)
  1591. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(
  1592. self.on_pf_color_spinner)
  1593. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(
  1594. self.on_pf_color_slider)
  1595. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(
  1596. self.on_pl_color_entry)
  1597. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(
  1598. self.on_pl_color_button)
  1599. # Setting selection (left - right) colors signals
  1600. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(
  1601. self.on_sf_color_entry)
  1602. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(
  1603. self.on_sf_color_button)
  1604. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(
  1605. self.on_sf_color_spinner)
  1606. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(
  1607. self.on_sf_color_slider)
  1608. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(
  1609. self.on_sl_color_entry)
  1610. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(
  1611. self.on_sl_color_button)
  1612. # Setting selection (right - left) colors signals
  1613. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(
  1614. self.on_alt_sf_color_entry)
  1615. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(
  1616. self.on_alt_sf_color_button)
  1617. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1618. self.on_alt_sf_color_spinner)
  1619. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1620. self.on_alt_sf_color_slider)
  1621. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(
  1622. self.on_alt_sl_color_entry)
  1623. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(
  1624. self.on_alt_sl_color_button)
  1625. # Setting Editor Draw colors signals
  1626. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(
  1627. self.on_draw_color_entry)
  1628. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(
  1629. self.on_draw_color_button)
  1630. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(
  1631. self.on_sel_draw_color_entry)
  1632. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(
  1633. self.on_sel_draw_color_button)
  1634. self.ui.general_defaults_form.general_gui_group.proj_color_entry.editingFinished.connect(
  1635. self.on_proj_color_entry)
  1636. self.ui.general_defaults_form.general_gui_group.proj_color_button.clicked.connect(
  1637. self.on_proj_color_button)
  1638. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.editingFinished.connect(
  1639. self.on_proj_color_dis_entry)
  1640. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.clicked.connect(
  1641. self.on_proj_color_dis_button)
  1642. # ########## workspace setting signals ###########
  1643. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1644. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1645. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1646. # ########## CNC Job related signals #############
  1647. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.tc_variable_combo.currentIndexChanged[str].connect(
  1648. self.on_cnc_custom_parameters)
  1649. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.editingFinished.connect(
  1650. self.on_annotation_fontcolor_entry)
  1651. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.clicked.connect(
  1652. self.on_annotation_fontcolor_button)
  1653. # ########## Tools related signals #############
  1654. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1655. self.on_film_color_entry)
  1656. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1657. self.on_film_color_button)
  1658. # ########## Modify G-CODE Plot Area TAB ###########
  1659. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1660. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1661. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1662. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1663. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1664. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1665. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1666. # portability changed signal
  1667. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1668. # Object list
  1669. self.collection.view.activated.connect(self.on_row_activated)
  1670. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1671. self.ui.general_defaults_form.general_gui_set_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1672. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1673. # Export Excellon parameters.
  1674. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1675. self.on_update_exc_export
  1676. )
  1677. # call it once to make sure it is updated at startup
  1678. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1679. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1680. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1681. self.on_excellon_defaults_button)
  1682. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1683. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1684. self.on_excellon_options_button)
  1685. # when there are arguments at application startup this get launched
  1686. self.args_at_startup[list].connect(self.on_startup_args)
  1687. # ##############################################################
  1688. # ############### FILE ASSOCIATIONS SIGNALS ####################
  1689. # ##############################################################
  1690. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1691. lambda: self.restore_extensions(ext_type='excellon'))
  1692. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1693. lambda: self.restore_extensions(ext_type='gcode'))
  1694. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1695. lambda: self.restore_extensions(ext_type='gerber'))
  1696. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1697. lambda: self.delete_all_extensions(ext_type='excellon'))
  1698. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1699. lambda: self.delete_all_extensions(ext_type='gcode'))
  1700. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1701. lambda: self.delete_all_extensions(ext_type='gerber'))
  1702. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1703. lambda: self.add_extension(ext_type='excellon'))
  1704. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1705. lambda: self.add_extension(ext_type='gcode'))
  1706. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1707. lambda: self.add_extension(ext_type='gerber'))
  1708. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1709. lambda: self.del_extension(ext_type='excellon'))
  1710. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1711. lambda: self.del_extension(ext_type='gcode'))
  1712. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1713. lambda: self.del_extension(ext_type='gerber'))
  1714. # connect the 'Apply' buttons from the Preferences/File Associations
  1715. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1716. lambda: self.on_register_files(obj_type='excellon'))
  1717. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1718. lambda: self.on_register_files(obj_type='gcode'))
  1719. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1720. lambda: self.on_register_files(obj_type='gerber'))
  1721. # ##############################################################
  1722. # ###################### KEYWORDS SIGNALS ######################
  1723. # ##############################################################
  1724. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1725. lambda: self.restore_extensions(ext_type='keyword'))
  1726. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1727. lambda: self.delete_all_extensions(ext_type='keyword'))
  1728. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1729. lambda: self.add_extension(ext_type='keyword'))
  1730. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1731. lambda: self.del_extension(ext_type='keyword'))
  1732. # splash screen button signal
  1733. self.ui.general_defaults_form.general_gui_set_group.splash_cb.stateChanged.connect(self.on_splash_changed)
  1734. # connect the abort_all_tasks related slots to the related signals
  1735. self.proc_container.idle_flag.connect(self.app_is_idle)
  1736. # #####################################################################################
  1737. # ########### FINISHED CONNECTING SIGNALS #############################################
  1738. # #####################################################################################
  1739. self.log.debug("Finished connecting Signals.")
  1740. # #####################################################################################
  1741. # ########################## Other setups #############################################
  1742. # #####################################################################################
  1743. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  1744. # depending on from where those tools are called different actions can be done
  1745. self.call_source = 'app'
  1746. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1747. self.tool_tab_locked = False
  1748. # decide if to show or hide the Notebook side of the screen at startup
  1749. if self.defaults["global_project_at_startup"] is True:
  1750. self.ui.splitter.setSizes([1, 1])
  1751. else:
  1752. self.ui.splitter.setSizes([0, 1])
  1753. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1754. self.setup_obj_classes()
  1755. self.setup_recent_items()
  1756. self.setup_component_editor()
  1757. # #####################################################################################
  1758. # ######################### Auto-complete KEYWORDS ####################################
  1759. # #####################################################################################
  1760. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1761. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1762. 'delete', 'drillcncjob', 'export_gcode', 'export_svg', 'ext', 'exteriors', 'follow',
  1763. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1764. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1765. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1766. 'mirror', 'ncc',
  1767. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1768. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'paint',
  1769. 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1770. 'save', 'save_project',
  1771. 'save_sys', 'scale',
  1772. 'set_active', 'set_sys', 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1773. 'version', 'write_gcode'
  1774. ]
  1775. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1776. 'Repetier', 'Roland_MDX_20', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1777. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'axis', 'axisoffset',
  1778. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1779. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dwell',
  1780. 'dwelltime', 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1781. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1782. 'milled_dias', 'minoffset', 'multidepth', 'name', 'offset', 'opt_type', 'order',
  1783. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1784. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1785. 'spacing_columns',
  1786. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'use_threads', 'value', 'x',
  1787. 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1788. ]
  1789. self.tcl_keywords = [
  1790. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1791. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1792. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1793. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1794. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1795. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1796. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1797. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1798. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1799. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1800. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1801. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1802. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1803. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1804. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1805. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1806. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1807. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1808. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1809. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1810. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1811. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1812. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1813. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1814. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1815. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1816. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1817. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1818. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1819. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1820. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1821. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1822. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1823. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1824. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1825. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1826. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1827. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1828. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1829. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1830. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1831. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1832. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1833. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1834. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1835. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1836. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1837. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1838. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1839. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1840. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1841. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1842. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1843. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1844. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1845. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1846. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1847. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1848. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1849. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1850. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1851. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1852. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1853. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1854. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1855. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1856. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1857. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  1858. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  1859. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  1860. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  1861. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  1862. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  1863. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  1864. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  1865. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  1866. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  1867. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  1868. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  1869. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  1870. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  1871. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  1872. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  1873. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  1874. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  1875. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  1876. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1877. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1878. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1879. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1880. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1881. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1882. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1883. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1884. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1885. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1886. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1887. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1888. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1889. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1890. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1891. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1892. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1893. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1894. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1895. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1896. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1897. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1898. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1899. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1900. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1901. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1902. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1903. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1904. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1905. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1906. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1907. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1908. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1909. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1910. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1911. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1912. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1913. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1914. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1915. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1916. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1917. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1918. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1919. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1920. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1921. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1922. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1923. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1924. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1925. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1926. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1927. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1928. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1929. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1930. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1931. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1932. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1933. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1934. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1935. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1936. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1937. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1938. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1939. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1940. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1941. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1942. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1943. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1944. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1945. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1946. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1947. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1948. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1949. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1950. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1951. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1952. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1953. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1954. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1955. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1956. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1957. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1958. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1959. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1960. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1961. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1962. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1963. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1964. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1965. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1966. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1967. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1968. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1969. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1970. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1971. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1972. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1973. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1974. ]
  1975. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1976. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1977. # ####################################################################################
  1978. # ####################### Shell SETUP ################################################
  1979. # ####################################################################################
  1980. self.shell = FCShell(self, version=self.version)
  1981. self.shell._edit.set_model_data(self.myKeywords)
  1982. self.ui.code_editor.set_model_data(self.myKeywords)
  1983. self.shell.setWindowIcon(self.ui.app_icon)
  1984. self.shell.setWindowTitle("FlatCAM Shell")
  1985. self.shell.resize(*self.defaults["global_shell_shape"])
  1986. self.shell.append_output("FlatCAM %s - " % self.version)
  1987. self.shell.append_output(_("Open Source Software - Type help to get started\n\n"))
  1988. self.init_tcl()
  1989. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1990. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1991. self.ui.shell_dock.setWidget(self.shell)
  1992. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1993. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1994. QtWidgets.QDockWidget.DockWidgetFloatable |
  1995. QtWidgets.QDockWidget.DockWidgetClosable)
  1996. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1997. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1998. if self.defaults["global_shell_at_startup"]:
  1999. self.ui.shell_dock.show()
  2000. else:
  2001. self.ui.shell_dock.hide()
  2002. # ##################################################################################
  2003. # ###################### Tools and Plugins #########################################
  2004. # ##################################################################################
  2005. self.dblsidedtool = None
  2006. self.measurement_tool = None
  2007. self.panelize_tool = None
  2008. self.film_tool = None
  2009. self.paste_tool = None
  2010. self.calculator_tool = None
  2011. self.sub_tool = None
  2012. self.move_tool = None
  2013. self.cutout_tool = None
  2014. self.ncclear_tool = None
  2015. self.paint_tool = None
  2016. self.transform_tool = None
  2017. self.properties_tool = None
  2018. self.pdf_tool = None
  2019. self.image_tool = None
  2020. self.pcb_wizard_tool = None
  2021. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2022. self.install_tools()
  2023. # ### System Font Parsing ###
  2024. # self.f_parse = ParseFont(self)
  2025. # self.parse_system_fonts()
  2026. # #####################################################################################
  2027. # ######################## Check for updates ##########################################
  2028. # #####################################################################################
  2029. # Separate thread (Not worker)
  2030. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2031. if (self.beta is False or self.beta is None) and \
  2032. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  2033. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2034. self.thr2 = QtCore.QThread()
  2035. self.worker_task.emit({'fcn': self.version_check,
  2036. 'params': []})
  2037. self.thr2.start(QtCore.QThread.LowPriority)
  2038. # #####################################################################################
  2039. # ######################### Register files with FlatCAM; #############################
  2040. # ######################### It works only for Windows for now ########################
  2041. # #####################################################################################
  2042. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2043. self.on_register_files()
  2044. # #####################################################################################
  2045. # ###################### Variables for global usage ###################################
  2046. # #####################################################################################
  2047. # coordinates for relative position display
  2048. self.rel_point1 = (0, 0)
  2049. self.rel_point2 = (0, 0)
  2050. # variable to store coordinates
  2051. self.pos = (0, 0)
  2052. self.pos_jump = (0, 0)
  2053. # variable to store mouse coordinates
  2054. self.mouse = [0, 0]
  2055. # decide if we have a double click or single click
  2056. self.doubleclick = False
  2057. # variable to store if a command is active (then the var is not None) and which one it is
  2058. self.command_active = None
  2059. # variable to store the status of moving selection action
  2060. # None value means that it's not an selection action
  2061. # True value = a selection from left to right
  2062. # False value = a selection from right to left
  2063. self.selection_type = None
  2064. # List to store the objects that are currently loaded in FlatCAM
  2065. # This list is updated on each object creation or object delete
  2066. self.all_objects_list = list()
  2067. # List to store the objects that are selected
  2068. self.sel_objects_list = list()
  2069. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2070. self.key_modifiers = None
  2071. # Variable to hold the status of the axis
  2072. self.toggle_axis = True
  2073. # Variable to store the status of the fullscreen event
  2074. self.toggle_fscreen = False
  2075. # Variable to store the status of the code editor
  2076. self.toggle_codeeditor = False
  2077. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2078. self.click_noproject = False
  2079. self.cursor = None
  2080. # Variable to store the GCODE that was edited
  2081. self.gcode_edited = ""
  2082. # reference for the self.ui.code_editor
  2083. self.reference_code_editor = None
  2084. self.script_code = ''
  2085. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2086. self.preferences_changed_flag = False
  2087. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2088. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2089. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2090. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2091. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2092. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2093. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ncp', 'out', 'plt', 'ply', 'rol', 'sbp',
  2094. 'tap', 'xpi']
  2095. self.svg_list = ['svg']
  2096. self.dxf_list = ['dxf']
  2097. self.pdf_list = ['pdf']
  2098. self.prj_list = ['flatprj']
  2099. self.conf_list = ['flatconfig']
  2100. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2101. # flag for polygons not cleared
  2102. self.poly_not_cleared = False
  2103. # VisPy visuals
  2104. self.isHovering = False
  2105. self.notHovering = True
  2106. # when True, the app has to return from any thread
  2107. self.abort_flag = False
  2108. # ###############################################################################
  2109. # ############# Save defaults to factory_defaults.FlatConfig file ###############
  2110. # ############# It's done only once after install ###############
  2111. # ###############################################################################
  2112. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  2113. fac_def_from_file = factory_file.read()
  2114. factory_defaults = json.loads(fac_def_from_file)
  2115. # if the file contain an empty dictionary then save the factory defaults into the file
  2116. if not factory_defaults:
  2117. self.save_factory_defaults(silent=False)
  2118. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  2119. initial_lay = 'compact'
  2120. self.on_layout(lay=initial_lay)
  2121. # Set the combobox in Preferences to the current layout
  2122. idx = self.ui.general_defaults_form.general_gui_set_group.layout_combo.findText(initial_lay)
  2123. self.ui.general_defaults_form.general_gui_set_group.layout_combo.setCurrentIndex(idx)
  2124. factory_file.close()
  2125. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  2126. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  2127. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  2128. # after the first run, this object should be False
  2129. self.defaults["first_run"] = False
  2130. # ###############################################################################
  2131. # ################# ADDING FlatCAM EDITORS section ##############################
  2132. # ###############################################################################
  2133. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2134. # at the first launch of the App , the editors will not be functional.
  2135. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2136. self.exc_editor = FlatCAMExcEditor(self)
  2137. self.grb_editor = FlatCAMGrbEditor(self)
  2138. self.log.debug("Finished adding FlatCAM Editor's.")
  2139. self.set_ui_title(name=_("New Project - Not saved"))
  2140. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2141. current_platform = platform.architecture()[0]
  2142. if current_platform != '64bit':
  2143. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2144. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2145. # ###############################################################################
  2146. # ####################### Finished the CONSTRUCTOR ##############################
  2147. # ###############################################################################
  2148. App.log.debug("END of constructor. Releasing control.")
  2149. # #####################################################################################
  2150. # ########################## SHOW GUI #################################################
  2151. # #####################################################################################
  2152. # if the app is not started as headless, show it
  2153. if self.cmd_line_headless != 1:
  2154. # finish the splash
  2155. self.splash.finish(self.ui)
  2156. settings = QSettings("Open Source", "FlatCAM")
  2157. if settings.contains("maximized_gui"):
  2158. maximized_ui = settings.value('maximized_gui', type=bool)
  2159. if maximized_ui is True:
  2160. self.ui.showMaximized()
  2161. else:
  2162. self.ui.show()
  2163. else:
  2164. self.ui.show()
  2165. if self.defaults["global_systray_icon"]:
  2166. self.trayIcon.show()
  2167. else:
  2168. log.warning("******************* RUNNING HEADLESS *******************")
  2169. # #####################################################################################
  2170. # ########################## START-UP ARGUMENTS #######################################
  2171. # #####################################################################################
  2172. # test if the program was started with a script as parameter
  2173. if self.cmd_line_shellvar:
  2174. try:
  2175. cnt = 0
  2176. command_tcl = 0
  2177. for i in self.cmd_line_shellvar.split(','):
  2178. if i is not None:
  2179. try:
  2180. command_tcl = eval(i)
  2181. except:
  2182. command_tcl = i
  2183. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2184. cnt += 1
  2185. # if there are Windows paths then replace the path separator with a Unix like one
  2186. if sys.platform == 'win32':
  2187. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2188. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2189. except Exception as ext:
  2190. print("ERROR: ", ext)
  2191. sys.exit(2)
  2192. if self.cmd_line_shellfile:
  2193. try:
  2194. if self.ui.shell_dock.isHidden():
  2195. self.ui.shell_dock.show()
  2196. with open(self.cmd_line_shellfile, "r") as myfile:
  2197. if show_splash:
  2198. self.splash.showMessage('%s: %ssec\n%s' % (
  2199. _("Canvas initialization started.\n"
  2200. "Canvas initialization finished in"), '%.2f' % self.used_time,
  2201. _("Executing Tcl Script ...")),
  2202. alignment=Qt.AlignBottom | Qt.AlignLeft,
  2203. color=QtGui.QColor("gray"))
  2204. cmd_line_shellfile_text = myfile.read()
  2205. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2206. except Exception as ext:
  2207. print("ERROR: ", ext)
  2208. sys.exit(2)
  2209. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2210. # the path/file_name must be enclosed in quotes if it contain spaces
  2211. if App.args:
  2212. self.args_at_startup.emit(App.args)
  2213. @staticmethod
  2214. def copy_and_overwrite(from_path, to_path):
  2215. """
  2216. From here:
  2217. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2218. :param from_path: source path
  2219. :param to_path: destination path
  2220. :return: None
  2221. """
  2222. if os.path.exists(to_path):
  2223. shutil.rmtree(to_path)
  2224. try:
  2225. shutil.copytree(from_path, to_path)
  2226. except FileNotFoundError:
  2227. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2228. shutil.copytree(from_new_path, to_path)
  2229. def on_startup_args(self, args, silent=False):
  2230. """
  2231. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2232. :param args: a list containing the application args at startup
  2233. :return: None
  2234. """
  2235. if args is not None:
  2236. args_to_process = args
  2237. else:
  2238. args_to_process = App.args
  2239. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2240. for argument in args_to_process:
  2241. if '.FlatPrj'.lower() in argument.lower():
  2242. try:
  2243. project_name = str(argument)
  2244. if project_name == "":
  2245. if silent is False:
  2246. self.inform.emit(_("Open cancelled."))
  2247. else:
  2248. # self.open_project(project_name)
  2249. run_from_arg = True
  2250. # self.worker_task.emit({'fcn': self.open_project,
  2251. # 'params': [project_name, run_from_arg]})
  2252. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2253. except Exception as e:
  2254. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2255. elif '.FlatConfig'.lower() in argument.lower():
  2256. try:
  2257. file_name = str(argument)
  2258. if file_name == "":
  2259. if silent is False:
  2260. self.inform.emit(_("Open Config file failed."))
  2261. else:
  2262. run_from_arg = True
  2263. # self.worker_task.emit({'fcn': self.open_config_file,
  2264. # 'params': [file_name, run_from_arg]})
  2265. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2266. except Exception as e:
  2267. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2268. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2269. try:
  2270. file_name = str(argument)
  2271. if file_name == "":
  2272. if silent is False:
  2273. self.inform.emit(_("Open Script file failed."))
  2274. else:
  2275. if silent is False:
  2276. self.on_fileopenscript(name=file_name)
  2277. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2278. self.on_filerunscript(name=file_name)
  2279. except Exception as e:
  2280. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2281. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2282. log.debug("App.on_startup_args() --> Quit event.")
  2283. sys.exit()
  2284. elif 'save'.lower() in argument.lower():
  2285. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2286. self.save_defaults()
  2287. else:
  2288. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2289. proc_arg = argument.lower()
  2290. for ext in exc_list:
  2291. proc_ext = ext.replace(' ', '')
  2292. proc_ext = '.%s' % proc_ext
  2293. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2294. file_name = str(argument)
  2295. if file_name == "":
  2296. if silent is False:
  2297. self.inform.emit(_("Open Excellon file failed."))
  2298. else:
  2299. self.on_fileopenexcellon(name=file_name)
  2300. return
  2301. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2302. for ext in gco_list:
  2303. proc_ext = ext.replace(' ', '')
  2304. proc_ext = '.%s' % proc_ext
  2305. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2306. print(proc_ext, proc_arg)
  2307. file_name = str(argument)
  2308. if file_name == "":
  2309. if silent is False:
  2310. self.inform.emit(_("Open GCode file failed."))
  2311. else:
  2312. self.on_fileopengcode(name=file_name)
  2313. return
  2314. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2315. for ext in grb_list:
  2316. proc_ext = ext.replace(' ', '')
  2317. proc_ext = '.%s' % proc_ext
  2318. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2319. file_name = str(argument)
  2320. if file_name == "":
  2321. if silent is False:
  2322. self.inform.emit(_("Open Gerber file failed."))
  2323. else:
  2324. self.on_fileopengerber(name=file_name)
  2325. return
  2326. # if it reached here without already returning then the app was registered with a file that it does not
  2327. # recognize therefore we must quit
  2328. sys.exit(2)
  2329. def set_ui_title(self, name):
  2330. """
  2331. Sets the title of the main window.
  2332. :param name: String that store the project path and project name
  2333. :return: None
  2334. """
  2335. self.ui.setWindowTitle('FlatCAM %s %s - %s %s' %
  2336. (self.version,
  2337. ('BETA' if self.beta else ''),
  2338. platform.architecture()[0],
  2339. name)
  2340. )
  2341. def defaults_read_form(self):
  2342. """
  2343. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2344. :return: None
  2345. """
  2346. for option in self.defaults_form_fields:
  2347. try:
  2348. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2349. except Exception as e:
  2350. log.debug("App.defaults_read_form() --> %s" % str(e))
  2351. def defaults_write_form(self, factor=None, fl_units=None):
  2352. """
  2353. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2354. self.defaults dictionary.
  2355. :param factor: will apply a factor to the values that written in the GUI elements
  2356. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2357. :return: None
  2358. """
  2359. for option in self.defaults:
  2360. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2361. # try:
  2362. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2363. # except KeyError:
  2364. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2365. # # TODO: Rethink this?
  2366. # pass
  2367. def defaults_write_form_field(self, field, factor=None, units=None):
  2368. """
  2369. Basically it is the worker in the self.defaults_write_form()
  2370. :param field: the GUI element in Preferences GUI to be updated
  2371. :param factor: factor to be applied to the field parameter
  2372. :param units: current FLatCAM measuring units
  2373. :return: None, it updates GUI elements
  2374. """
  2375. try:
  2376. if factor is None:
  2377. if units is None:
  2378. self.defaults_form_fields[field].set_value(self.defaults[field])
  2379. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2380. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=6)
  2381. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2382. self.defaults_form_fields[field].set_value(self.defaults[field], decimals=4)
  2383. else:
  2384. if units is None:
  2385. self.defaults_form_fields[field].set_value(self.defaults[field] * factor)
  2386. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2387. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=6)
  2388. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2389. self.defaults_form_fields[field].set_value((self.defaults[field] * factor), decimals=4)
  2390. except KeyError:
  2391. # self.log.debug("defaults_write_form(): No field for: %s" % option)
  2392. # TODO: Rethink this?
  2393. pass
  2394. except AttributeError:
  2395. log.debug(field)
  2396. def clear_pool(self):
  2397. """
  2398. Clear the multiprocessing pool and calls garbage collector.
  2399. :return: None
  2400. """
  2401. self.pool.close()
  2402. self.pool = Pool()
  2403. self.pool_recreated.emit(self.pool)
  2404. gc.collect()
  2405. def install_tools(self):
  2406. """
  2407. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2408. Instantiation of the Tools classes.
  2409. The order that the tools are installed is important as they can depend on each other install position.
  2410. :return: None
  2411. """
  2412. self.dblsidedtool = DblSidedTool(self)
  2413. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  2414. self.measurement_tool = Measurement(self)
  2415. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  2416. self.panelize_tool = Panelize(self)
  2417. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  2418. self.film_tool = Film(self)
  2419. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  2420. self.paste_tool = SolderPaste(self)
  2421. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'))
  2422. self.calculator_tool = ToolCalculator(self)
  2423. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'), separator=True)
  2424. self.sub_tool = ToolSub(self)
  2425. self.sub_tool.install(icon=QtGui.QIcon('share/sub32.png'), pos=self.ui.menutool, separator=True)
  2426. self.move_tool = ToolMove(self)
  2427. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  2428. before=self.ui.menueditorigin)
  2429. self.cutout_tool = CutOut(self)
  2430. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16_bis.png'), pos=self.ui.menutool,
  2431. before=self.measurement_tool.menuAction)
  2432. self.ncclear_tool = NonCopperClear(self)
  2433. self.ncclear_tool.install(icon=QtGui.QIcon('share/ncc16.png'), pos=self.ui.menutool,
  2434. before=self.measurement_tool.menuAction, separator=True)
  2435. self.paint_tool = ToolPaint(self)
  2436. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  2437. before=self.measurement_tool.menuAction, separator=True)
  2438. self.transform_tool = ToolTransform(self)
  2439. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  2440. self.properties_tool = Properties(self)
  2441. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  2442. self.pdf_tool = ToolPDF(self)
  2443. self.pdf_tool.install(icon=QtGui.QIcon('share/pdf32.png'), pos=self.ui.menufileimport,
  2444. separator=True)
  2445. self.image_tool = ToolImage(self)
  2446. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  2447. separator=True)
  2448. self.pcb_wizard_tool = PcbWizard(self)
  2449. self.pcb_wizard_tool.install(icon=QtGui.QIcon('share/drill32.png'), pos=self.ui.menufileimport)
  2450. self.log.debug("Tools are installed.")
  2451. def remove_tools(self):
  2452. """
  2453. Will remove all the actions in the Tool menu.
  2454. :return: None
  2455. """
  2456. for act in self.ui.menutool.actions():
  2457. self.ui.menutool.removeAction(act)
  2458. def init_tools(self):
  2459. """
  2460. Initialize the Tool tab in the notebook side of the central widget.
  2461. Remove the actions in the Tools menu.
  2462. Instantiate again the FlatCAM tools (plugins).
  2463. All this is required when changing the layout: standard, compact etc.
  2464. :return: None
  2465. """
  2466. log.debug("init_tools()")
  2467. # delete the data currently in the Tools Tab and the Tab itself
  2468. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2469. if widget is not None:
  2470. widget.deleteLater()
  2471. self.ui.notebook.removeTab(2)
  2472. # rebuild the Tools Tab
  2473. self.ui.tool_tab = QtWidgets.QWidget()
  2474. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2475. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2476. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2477. self.ui.tool_scroll_area = VerticalScrollArea()
  2478. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2479. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2480. # first remove all of them
  2481. self.remove_tools()
  2482. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2483. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  2484. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2485. # third install all of them
  2486. self.install_tools()
  2487. self.log.debug("Tools are initialized.")
  2488. # def parse_system_fonts(self):
  2489. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2490. # 'params': []})
  2491. def connect_toolbar_signals(self):
  2492. """
  2493. Reconnect the signals to the actions in the toolbar.
  2494. This has to be done each time after the FlatCAM tools are removed/installed.
  2495. :return: None
  2496. """
  2497. # Toolbar
  2498. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2499. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2500. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2501. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2502. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2503. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2504. self.ui.replot_btn.triggered.connect(self.plot_all)
  2505. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2506. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2507. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2508. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2509. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2510. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2511. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2512. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2513. self.ui.delete_btn.triggered.connect(self.on_delete)
  2514. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2515. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2516. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2517. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2518. # Tools Toolbar Signals
  2519. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2520. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2521. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2522. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2523. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2524. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2525. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2526. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2527. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2528. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2529. def object2editor(self):
  2530. """
  2531. Send the current Geometry or Excellon object (if any) into the it's editor.
  2532. :return: None
  2533. """
  2534. self.report_usage("object2editor()")
  2535. edited_object = self.collection.get_active()
  2536. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2537. isinstance(edited_object, FlatCAMExcellon):
  2538. pass
  2539. else:
  2540. self.inform.emit('[WARNING_NOTCL] %s' %
  2541. _("Select a Geometry, Gerber or Excellon Object to edit."))
  2542. return
  2543. if isinstance(edited_object, FlatCAMGeometry):
  2544. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2545. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2546. # we set the notebook to hidden
  2547. self.ui.splitter.setSizes([0, 1])
  2548. if edited_object.multigeo is True:
  2549. edited_tools = [int(x.text()) for x in edited_object.ui.geo_tools_table.selectedItems()]
  2550. if len(edited_tools) > 1:
  2551. self.inform.emit('[WARNING_NOTCL] %s' %
  2552. _("Simultanoeus editing of tools geometry in a MultiGeo Geometry "
  2553. "is not possible.\n"
  2554. "Edit only one geometry at a time."))
  2555. # determine the tool dia of the selected tool
  2556. selected_tooldia = float(edited_object.ui.geo_tools_table.item((edited_tools[0] - 1), 1).text())
  2557. # now find the key in the edited_object.tools that has this tooldia
  2558. multi_tool = 1
  2559. for tool in edited_object.tools:
  2560. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2561. multi_tool = tool
  2562. break
  2563. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2564. else:
  2565. self.geo_editor.edit_fcgeometry(edited_object)
  2566. # set call source to the Editor we go into
  2567. self.call_source = 'geo_editor'
  2568. elif isinstance(edited_object, FlatCAMExcellon):
  2569. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2570. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2571. if self.ui.splitter.sizes()[0] == 0:
  2572. self.ui.splitter.setSizes([1, 1])
  2573. self.exc_editor.edit_fcexcellon(edited_object)
  2574. # set call source to the Editor we go into
  2575. self.call_source = 'exc_editor'
  2576. elif isinstance(edited_object, FlatCAMGerber):
  2577. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2578. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2579. if self.ui.splitter.sizes()[0] == 0:
  2580. self.ui.splitter.setSizes([1, 1])
  2581. self.grb_editor.edit_fcgerber(edited_object)
  2582. # set call source to the Editor we go into
  2583. self.call_source = 'grb_editor'
  2584. # make sure that we can't select another object while in Editor Mode:
  2585. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2586. self.ui.project_frame.setDisabled(True)
  2587. # delete any selection shape that might be active as they are not relevant in Editor
  2588. self.delete_selection_shape()
  2589. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2590. self.ui.plot_tab_area.protectTab(0)
  2591. self.inform.emit('[WARNING_NOTCL] %s' %
  2592. _("Editor is activated ..."))
  2593. self.should_we_save = True
  2594. def editor2object(self, cleanup=None):
  2595. """
  2596. Transfers the Geometry or Excellon from it's editor to the current object.
  2597. :return: None
  2598. """
  2599. self.report_usage("editor2object()")
  2600. # do not update a geometry or excellon object unless it comes out of an editor
  2601. if self.call_source != 'app':
  2602. edited_obj = self.collection.get_active()
  2603. if cleanup is None:
  2604. msgbox = QtWidgets.QMessageBox()
  2605. msgbox.setText(_("Do you want to save the edited object?"))
  2606. msgbox.setWindowTitle(_("Close Editor"))
  2607. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2608. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2609. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2610. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2611. msgbox.setDefaultButton(bt_yes)
  2612. msgbox.exec_()
  2613. response = msgbox.clickedButton()
  2614. if response == bt_yes:
  2615. # clean the Tools Tab
  2616. self.ui.tool_scroll_area.takeWidget()
  2617. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2618. self.ui.notebook.setTabText(2, "Tool")
  2619. if isinstance(edited_obj, FlatCAMGeometry):
  2620. obj_type = "Geometry"
  2621. if cleanup is None:
  2622. self.geo_editor.update_fcgeometry(edited_obj)
  2623. self.geo_editor.update_options(edited_obj)
  2624. self.geo_editor.deactivate()
  2625. # update the geo object options so it is including the bounding box values
  2626. try:
  2627. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2628. edited_obj.options['xmin'] = xmin
  2629. edited_obj.options['ymin'] = ymin
  2630. edited_obj.options['xmax'] = xmax
  2631. edited_obj.options['ymax'] = ymax
  2632. except AttributeError as e:
  2633. self.inform.emit('[WARNING] %s' %
  2634. _("Object empty after edit."))
  2635. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2636. elif isinstance(edited_obj, FlatCAMGerber):
  2637. obj_type = "Gerber"
  2638. if cleanup is None:
  2639. self.grb_editor.update_fcgerber()
  2640. self.grb_editor.update_options(edited_obj)
  2641. self.grb_editor.deactivate_grb_editor()
  2642. # delete the old object (the source object) if it was an empty one
  2643. if len(edited_obj.solid_geometry) == 0:
  2644. old_name = edited_obj.options['name']
  2645. self.collection.set_active(old_name)
  2646. self.collection.delete_active()
  2647. elif isinstance(edited_obj, FlatCAMExcellon):
  2648. obj_type = "Excellon"
  2649. if cleanup is None:
  2650. self.exc_editor.update_fcexcellon(edited_obj)
  2651. self.exc_editor.update_options(edited_obj)
  2652. self.exc_editor.deactivate()
  2653. else:
  2654. self.inform.emit('[WARNING_NOTCL] %s' %
  2655. _("Select a Gerber, Geometry or Excellon Object to update."))
  2656. return
  2657. self.inform.emit('[selected] %s %s' %
  2658. (obj_type, _("is updated, returning to App...")))
  2659. elif response == bt_no:
  2660. # clean the Tools Tab
  2661. self.ui.tool_scroll_area.takeWidget()
  2662. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2663. self.ui.notebook.setTabText(2, "Tool")
  2664. if isinstance(edited_obj, FlatCAMGeometry):
  2665. self.geo_editor.deactivate()
  2666. elif isinstance(edited_obj, FlatCAMGerber):
  2667. self.grb_editor.deactivate_grb_editor()
  2668. elif isinstance(edited_obj, FlatCAMExcellon):
  2669. self.exc_editor.deactivate()
  2670. # set focus on the project tab
  2671. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  2672. else:
  2673. self.inform.emit('[WARNING_NOTCL] %s' %
  2674. _("Select a Gerber, Geometry or Excellon Object to update."))
  2675. return
  2676. elif response == bt_cancel:
  2677. return
  2678. else:
  2679. if isinstance(edited_obj, FlatCAMGeometry):
  2680. self.geo_editor.deactivate()
  2681. elif isinstance(edited_obj, FlatCAMGerber):
  2682. self.grb_editor.deactivate_grb_editor()
  2683. elif isinstance(edited_obj, FlatCAMExcellon):
  2684. self.exc_editor.deactivate()
  2685. else:
  2686. self.inform.emit('[WARNING_NOTCL] %s' %
  2687. _("Select a Gerber, Geometry or Excellon Object to update."))
  2688. return
  2689. # if notebook is hidden we show it
  2690. if self.ui.splitter.sizes()[0] == 0:
  2691. self.ui.splitter.setSizes([1, 1])
  2692. # restore the call_source to app
  2693. self.call_source = 'app'
  2694. edited_obj.plot()
  2695. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  2696. self.ui.plot_tab_area.protectTab(0)
  2697. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  2698. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  2699. self.ui.project_frame.setDisabled(False)
  2700. def get_last_folder(self):
  2701. """
  2702. Get the folder path from where the last file was opened.
  2703. :return: String, last opened folder path
  2704. """
  2705. return self.defaults["global_last_folder"]
  2706. def get_last_save_folder(self):
  2707. """
  2708. Get the folder path from where the last file was saved.
  2709. :return: String, last saved folder path
  2710. """
  2711. loc = self.defaults["global_last_save_folder"]
  2712. if loc is None:
  2713. loc = self.defaults["global_last_folder"]
  2714. if loc is None:
  2715. loc = os.path.dirname(__file__)
  2716. return loc
  2717. def report_usage(self, resource):
  2718. """
  2719. Increments usage counter for the given resource
  2720. in self.defaults['global_stats'].
  2721. :param resource: Name of the resource.
  2722. :return: None
  2723. """
  2724. if resource in self.defaults['global_stats']:
  2725. self.defaults['global_stats'][resource] += 1
  2726. else:
  2727. self.defaults['global_stats'][resource] = 1
  2728. def init_tcl(self):
  2729. """
  2730. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  2731. :return: None
  2732. """
  2733. if hasattr(self, 'tcl'):
  2734. # self.tcl = None
  2735. # TODO we need to clean non default variables and procedures here
  2736. # new object cannot be used here as it will not remember values created for next passes,
  2737. # because tcl was execudted in old instance of TCL
  2738. pass
  2739. else:
  2740. self.tcl = tk.Tcl()
  2741. self.setup_shell()
  2742. self.log.debug("TCL Shell has been initialized.")
  2743. # TODO: This shouldn't be here.
  2744. class TclErrorException(Exception):
  2745. """
  2746. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  2747. """
  2748. pass
  2749. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  2750. """
  2751. Shows a message on the FlatCAM Shell
  2752. :param msg: Message to display.
  2753. :param show: Opens the shell.
  2754. :param error: Shows the message as an error.
  2755. :param warning: Shows the message as an warning.
  2756. :param success: Shows the message as an success.
  2757. :param selected: Indicate that something was selected on canvas
  2758. :return: None
  2759. """
  2760. if show:
  2761. self.ui.shell_dock.show()
  2762. try:
  2763. if error:
  2764. self.shell.append_error(msg + "\n")
  2765. elif warning:
  2766. self.shell.append_warning(msg + "\n")
  2767. elif success:
  2768. self.shell.append_success(msg + "\n")
  2769. elif selected:
  2770. self.shell.append_selected(msg + "\n")
  2771. else:
  2772. self.shell.append_output(msg + "\n")
  2773. except AttributeError:
  2774. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  2775. def raise_tcl_unknown_error(self, unknownException):
  2776. """
  2777. Raise exception if is different type than TclErrorException
  2778. this is here mainly to show unknown errors inside TCL shell console.
  2779. :param unknownException:
  2780. :return:
  2781. """
  2782. if not isinstance(unknownException, self.TclErrorException):
  2783. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  2784. else:
  2785. raise unknownException
  2786. def display_tcl_error(self, error, error_info=None):
  2787. """
  2788. Escape bracket [ with '\' otherwise there is error
  2789. "ERROR: missing close-bracket" instead of real error
  2790. :param error: it may be text or exception
  2791. :param error_info: Some informations about the error
  2792. :return: None
  2793. """
  2794. if isinstance(error, Exception):
  2795. exc_type, exc_value, exc_traceback = error_info
  2796. if not isinstance(error, self.TclErrorException):
  2797. show_trace = 1
  2798. else:
  2799. show_trace = int(self.defaults['global_verbose_error_level'])
  2800. if show_trace > 0:
  2801. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  2802. trc_formated = []
  2803. for a in reversed(trc):
  2804. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  2805. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  2806. else:
  2807. text = "%s" % error
  2808. else:
  2809. text = error
  2810. text = text.replace('[', '\\[').replace('"', '\\"')
  2811. self.tcl.eval('return -code error "%s"' % text)
  2812. def raise_tcl_error(self, text):
  2813. """
  2814. This method pass exception from python into TCL as error, so we get stacktrace and reason
  2815. :param text: text of error
  2816. :return: raise exception
  2817. """
  2818. self.display_tcl_error(text)
  2819. raise self.TclErrorException(text)
  2820. def exec_command(self, text, no_echo=False):
  2821. """
  2822. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2823. Also handles execution in separated threads
  2824. :param text: FlatCAM TclCommand with parameters
  2825. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2826. will create crashes of the _Expandable_Edit widget
  2827. :return: output if there was any
  2828. """
  2829. self.report_usage('exec_command')
  2830. result = self.exec_command_test(text, False, no_echo=no_echo)
  2831. # MS: added this method call so the geometry is updated once the TCL command is executed
  2832. # if no_plot is None:
  2833. # self.plot_all()
  2834. return result
  2835. def exec_command_test(self, text, reraise=True, no_echo=False):
  2836. """
  2837. Same as exec_command(...) with additional control over exceptions.
  2838. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  2839. :param text: Input command
  2840. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  2841. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  2842. will create crashes of the _Expandable_Edit widget
  2843. :return: Output from the command
  2844. """
  2845. tcl_command_string = str(text)
  2846. try:
  2847. if no_echo is False:
  2848. self.shell.open_proccessing() # Disables input box.
  2849. result = self.tcl.eval(str(tcl_command_string))
  2850. if result != 'None' and no_echo is False:
  2851. self.shell.append_output(result + '\n')
  2852. except tk.TclError as e:
  2853. # This will display more precise answer if something in TCL shell fails
  2854. result = self.tcl.eval("set errorInfo")
  2855. self.log.error("Exec command Exception: %s" % (result + '\n'))
  2856. if no_echo is False:
  2857. self.shell.append_error('ERROR: ' + result + '\n')
  2858. # Show error in console and just return or in test raise exception
  2859. if reraise:
  2860. raise e
  2861. finally:
  2862. if no_echo is False:
  2863. self.shell.close_proccessing()
  2864. pass
  2865. return result
  2866. # """
  2867. # Code below is unsused. Saved for later.
  2868. # """
  2869. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  2870. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  2871. # self.log.debug(parts)
  2872. # try:
  2873. # if parts[0] not in commands:
  2874. # self.shell.append_error("Unknown command\n")
  2875. # return
  2876. #
  2877. # #import inspect
  2878. # #inspect.getargspec(someMethod)
  2879. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  2880. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  2881. # self.shell.append_error(
  2882. # "Command %s takes %d arguments. %d given.\n" %
  2883. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  2884. # )
  2885. # return
  2886. #
  2887. # cmdfcn = commands[parts[0]]["fcn"]
  2888. # cmdconv = commands[parts[0]]["converters"]
  2889. # if len(parts) - 1 > 0:
  2890. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  2891. # else:
  2892. # retval = cmdfcn()
  2893. # retfcn = commands[parts[0]]["retfcn"]
  2894. # if retval and retfcn(retval):
  2895. # self.shell.append_output(retfcn(retval) + "\n")
  2896. #
  2897. # except Exception as e:
  2898. # #self.shell.append_error(''.join(traceback.format_exc()))
  2899. # #self.shell.append_error("?\n")
  2900. # self.shell.append_error(str(e) + "\n")
  2901. def info(self, msg):
  2902. """
  2903. Informs the user. Normally on the status bar, optionally
  2904. also on the shell.
  2905. :param msg: Text to write.
  2906. :return: None
  2907. """
  2908. # Type of message in brackets at the beginning of the message.
  2909. match = re.search("\[([^\]]+)\](.*)", msg)
  2910. if match:
  2911. level = match.group(1)
  2912. msg_ = match.group(2)
  2913. self.ui.fcinfo.set_status(str(msg_), level=level)
  2914. if level.lower() == "error":
  2915. self.shell_message(msg, error=True, show=True)
  2916. elif level.lower() == "warning":
  2917. self.shell_message(msg, warning=True, show=True)
  2918. elif level.lower() == "error_notcl":
  2919. self.shell_message(msg, error=True, show=False)
  2920. elif level.lower() == "warning_notcl":
  2921. self.shell_message(msg, warning=True, show=False)
  2922. elif level.lower() == "success":
  2923. self.shell_message(msg, success=True, show=False)
  2924. elif level.lower() == "selected":
  2925. self.shell_message(msg, selected=True, show=False)
  2926. else:
  2927. self.shell_message(msg, show=False)
  2928. else:
  2929. self.ui.fcinfo.set_status(str(msg), level="info")
  2930. # make sure that if the message is to clear the infobar with a space
  2931. # is not printed over and over on the shell
  2932. if msg != '':
  2933. self.shell_message(msg)
  2934. def restore_toolbar_view(self):
  2935. """
  2936. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  2937. was saved in the defaults dictionary.
  2938. :return: None
  2939. """
  2940. tb = self.defaults["global_toolbar_view"]
  2941. if tb & 1:
  2942. self.ui.toolbarfile.setVisible(True)
  2943. else:
  2944. self.ui.toolbarfile.setVisible(False)
  2945. if tb & 2:
  2946. self.ui.toolbargeo.setVisible(True)
  2947. else:
  2948. self.ui.toolbargeo.setVisible(False)
  2949. if tb & 4:
  2950. self.ui.toolbarview.setVisible(True)
  2951. else:
  2952. self.ui.toolbarview.setVisible(False)
  2953. if tb & 8:
  2954. self.ui.toolbartools.setVisible(True)
  2955. else:
  2956. self.ui.toolbartools.setVisible(False)
  2957. if tb & 16:
  2958. self.ui.exc_edit_toolbar.setVisible(True)
  2959. else:
  2960. self.ui.exc_edit_toolbar.setVisible(False)
  2961. if tb & 32:
  2962. self.ui.geo_edit_toolbar.setVisible(True)
  2963. else:
  2964. self.ui.geo_edit_toolbar.setVisible(False)
  2965. if tb & 64:
  2966. self.ui.grb_edit_toolbar.setVisible(True)
  2967. else:
  2968. self.ui.grb_edit_toolbar.setVisible(False)
  2969. if tb & 128:
  2970. self.ui.snap_toolbar.setVisible(True)
  2971. else:
  2972. self.ui.snap_toolbar.setVisible(False)
  2973. if tb & 256:
  2974. self.ui.toolbarshell.setVisible(True)
  2975. else:
  2976. self.ui.toolbarshell.setVisible(False)
  2977. def load_defaults(self, filename):
  2978. """
  2979. Loads the aplication's default settings from current_defaults.FlatConfig into
  2980. ``self.defaults``.
  2981. :return: None
  2982. """
  2983. try:
  2984. f = open(self.data_path + "/" + filename + ".FlatConfig")
  2985. options = f.read()
  2986. f.close()
  2987. except IOError:
  2988. self.log.error("Could not load defaults file.")
  2989. self.inform.emit('[ERROR] %s' %
  2990. _("Could not load defaults file."))
  2991. # in case the defaults file can't be loaded, show all toolbars
  2992. self.defaults["global_toolbar_view"] = 511
  2993. return
  2994. try:
  2995. defaults = json.loads(options)
  2996. except:
  2997. # in case the defaults file can't be loaded, show all toolbars
  2998. self.defaults["global_toolbar_view"] = 511
  2999. e = sys.exc_info()[0]
  3000. App.log.error(str(e))
  3001. self.inform.emit('[ERROR] %s' %
  3002. _("Failed to parse defaults file."))
  3003. return
  3004. self.defaults.update(defaults)
  3005. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3006. # restore the toolbar view
  3007. self.restore_toolbar_view()
  3008. def on_import_preferences(self):
  3009. """
  3010. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  3011. ``self.defaults``.
  3012. :return: None
  3013. """
  3014. self.report_usage("on_import_preferences")
  3015. App.log.debug("on_import_preferences()")
  3016. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3017. try:
  3018. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3019. directory=self.data_path,
  3020. filter=filter_)
  3021. except TypeError:
  3022. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3023. filter=filter_)
  3024. filename = str(filename)
  3025. if filename == "":
  3026. self.inform.emit('[WARNING_NOTCL] %s' %
  3027. _("FlatCAM preferences import cancelled."))
  3028. else:
  3029. try:
  3030. f = open(filename)
  3031. options = f.read()
  3032. f.close()
  3033. except IOError:
  3034. self.log.error("Could not load defaults file.")
  3035. self.inform.emit('[ERROR_NOTCL] %s' %
  3036. _("Could not load defaults file."))
  3037. return
  3038. try:
  3039. defaults_from_file = json.loads(options)
  3040. except Exception as e:
  3041. e = sys.exc_info()[0]
  3042. App.log.error(str(e))
  3043. self.inform.emit('[ERROR_NOTCL] %s' %
  3044. _("Failed to parse defaults file."))
  3045. return
  3046. self.defaults.update(defaults_from_file)
  3047. self.on_preferences_edited()
  3048. self.inform.emit('[success] %s: %s' %
  3049. (_("Imported Defaults from"), filename))
  3050. def on_export_preferences(self):
  3051. """
  3052. Save the defaults dictionary to a file.
  3053. :return: None
  3054. """
  3055. self.report_usage("on_export_preferences")
  3056. App.log.debug("on_export_preferences()")
  3057. defaults_file_content = None
  3058. self.date = str(datetime.today()).rpartition('.')[0]
  3059. self.date = ''.join(c for c in self.date if c not in ':-')
  3060. self.date = self.date.replace(' ', '_')
  3061. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3062. try:
  3063. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3064. caption=_("Export FlatCAM Preferences"),
  3065. directory=self.data_path + '/preferences_' + self.date,
  3066. filter=filter__
  3067. )
  3068. except TypeError:
  3069. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3070. filter=filter__)
  3071. filename = str(filename)
  3072. defaults_from_file = {}
  3073. if filename == "":
  3074. self.inform.emit('[WARNING_NOTCL] %s' %
  3075. _("FlatCAM preferences export cancelled."))
  3076. return
  3077. else:
  3078. try:
  3079. f = open(filename, 'w')
  3080. defaults_file_content = f.read()
  3081. f.close()
  3082. except PermissionError:
  3083. self.inform.emit('[WARNING] %s' %
  3084. _("Permission denied, saving not possible.\n"
  3085. "Most likely another app is holding the file open and not accessible."))
  3086. return
  3087. except IOError:
  3088. App.log.debug('Creating a new preferences file ...')
  3089. f = open(filename, 'w')
  3090. json.dump({}, f)
  3091. f.close()
  3092. except:
  3093. e = sys.exc_info()[0]
  3094. App.log.error("Could not load defaults file.")
  3095. App.log.error(str(e))
  3096. self.inform.emit('[ERROR_NOTCL] %s' %
  3097. _("Could not load preferences file."))
  3098. return
  3099. try:
  3100. defaults_from_file = json.loads(defaults_file_content)
  3101. except:
  3102. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3103. # Update options
  3104. self.defaults_read_form()
  3105. defaults_from_file.update(self.defaults)
  3106. self.propagate_defaults(silent=True)
  3107. # Save update options
  3108. try:
  3109. f = open(filename, "w")
  3110. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3111. f.close()
  3112. except:
  3113. self.inform.emit('[ERROR_NOTCL] %s' %
  3114. _("Failed to write defaults to file."))
  3115. return
  3116. if self.defaults["global_open_style"] is False:
  3117. self.file_opened.emit("preferences", filename)
  3118. self.file_saved.emit("preferences", filename)
  3119. self.inform.emit('[success] %s: %s' %
  3120. (_("Exported preferences to"), filename))
  3121. def on_preferences_open_folder(self):
  3122. """
  3123. Will open an Explorer window set to the folder path where the FlatCAM preferences files are usually saved.
  3124. :return: None
  3125. """
  3126. self.report_usage("on_preferences_open_folder()")
  3127. if sys.platform == 'win32':
  3128. subprocess.Popen('explorer %s' % self.data_path)
  3129. elif sys.platform == 'darwin':
  3130. os.system('open "%s"' % self.data_path)
  3131. else:
  3132. subprocess.Popen(['xdg-open', self.data_path])
  3133. self.inform.emit('[success] %s' %
  3134. _("FlatCAM Preferences Folder opened."))
  3135. def save_geometry(self, x, y, width, height, notebook_width):
  3136. """
  3137. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3138. launch of the application.
  3139. :param x: X position of the main window
  3140. :param y: Y position of the main window
  3141. :param width: width of the main window
  3142. :param height: height of the main window
  3143. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3144. :return: None
  3145. """
  3146. self.defaults["global_def_win_x"] = x
  3147. self.defaults["global_def_win_y"] = y
  3148. self.defaults["global_def_win_w"] = width
  3149. self.defaults["global_def_win_h"] = height
  3150. self.defaults["global_def_notebook_width"] = notebook_width
  3151. self.save_defaults()
  3152. def message_dialog(self, title, message, kind="info"):
  3153. """
  3154. Builds and show a custom QMessageBox to be used in FlatCAM.
  3155. :param title: title of the QMessageBox
  3156. :param message: message to be displayed
  3157. :param kind: type of QMessageBox; will display a specific icon.
  3158. :return:
  3159. """
  3160. icon = {"info": QtWidgets.QMessageBox.Information,
  3161. "warning": QtWidgets.QMessageBox.Warning,
  3162. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3163. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3164. dlg.setText(message)
  3165. dlg.exec_()
  3166. def register_recent(self, kind, filename):
  3167. """
  3168. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3169. dictionary.
  3170. :param kind: type of file that was opened
  3171. :param filename: the path and file name for the file that was opened
  3172. :return:
  3173. """
  3174. self.log.debug("register_recent()")
  3175. self.log.debug(" %s" % kind)
  3176. self.log.debug(" %s" % filename)
  3177. record = {'kind': str(kind), 'filename': str(filename)}
  3178. if record in self.recent:
  3179. return
  3180. if record in self.recent_projects:
  3181. return
  3182. if record['kind'] == 'project':
  3183. self.recent_projects.insert(0, record)
  3184. else:
  3185. self.recent.insert(0, record)
  3186. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3187. self.recent.pop()
  3188. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3189. self.recent_projects.pop()
  3190. try:
  3191. f = open(self.data_path + '/recent.json', 'w')
  3192. except IOError:
  3193. App.log.error("Failed to open recent items file for writing.")
  3194. self.inform.emit('[ERROR_NOTCL] %s' %
  3195. _('Failed to open recent files file for writing.'))
  3196. return
  3197. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3198. f.close()
  3199. try:
  3200. fp = open(self.data_path + '/recent_projects.json', 'w')
  3201. except IOError:
  3202. App.log.error("Failed to open recent items file for writing.")
  3203. self.inform.emit('[ERROR_NOTCL] %s' %
  3204. _('Failed to open recent projects file for writing.'))
  3205. return
  3206. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3207. fp.close()
  3208. # Re-build the recent items menu
  3209. self.setup_recent_items()
  3210. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3211. """
  3212. Creates a new specialized FlatCAMObj and attaches it to the application,
  3213. this is, updates the GUI accordingly, any other records and plots it.
  3214. This method is thread-safe.
  3215. Notes:
  3216. * If the name is in use, the self.collection will modify it
  3217. when appending it to the collection. There is no need to handle
  3218. name conflicts here.
  3219. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3220. :type kind: str
  3221. :param name: Name for the object.
  3222. :type name: str
  3223. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3224. The function is called with 2 parameters: the new object and the App instance.
  3225. :type initialize: function
  3226. :param active:
  3227. :param fit:
  3228. :param plot: If to plot the resulting object
  3229. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3230. self.colleaction
  3231. :return: None
  3232. :rtype: None
  3233. """
  3234. App.log.debug("new_object()")
  3235. obj_plot = plot
  3236. obj_autoselected = autoselected
  3237. t0 = time.time() # Debug
  3238. # ## Create object
  3239. classdict = {
  3240. "gerber": FlatCAMGerber,
  3241. "excellon": FlatCAMExcellon,
  3242. "cncjob": FlatCAMCNCjob,
  3243. "geometry": FlatCAMGeometry
  3244. }
  3245. App.log.debug("Calling object constructor...")
  3246. obj = classdict[kind](name)
  3247. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3248. # Set options from "Project options" form
  3249. self.options_read_form()
  3250. # IMPORTANT
  3251. # The key names in defaults and options dictionary's are not random:
  3252. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3253. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  3254. # the options from project options form into the self.options. After that, below, depending on the type of
  3255. # object that is created, it will strip the name of the object and the underline (if the original key was
  3256. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3257. # "toolchange"
  3258. for option in self.options:
  3259. if option.find(kind + "_") == 0:
  3260. oname = option[len(kind) + 1:]
  3261. obj.options[oname] = self.options[option]
  3262. obj.isHovering = False
  3263. obj.notHovering = True
  3264. # Initialize as per user request
  3265. # User must take care to implement initialize
  3266. # in a thread-safe way as is is likely that we
  3267. # have been invoked in a separate thread.
  3268. t1 = time.time()
  3269. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3270. try:
  3271. return_value = initialize(obj, self)
  3272. except Exception as e:
  3273. msg = '[ERROR_NOTCL] %s' % \
  3274. _("An internal error has ocurred. See shell.\n")
  3275. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3276. msg += traceback.format_exc()
  3277. self.inform.emit(msg)
  3278. # if str(e) == "Empty Geometry":
  3279. # self.inform.emit("[ERROR_NOTCL] )
  3280. # else:
  3281. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  3282. return "fail"
  3283. t2 = time.time()
  3284. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3285. if return_value == 'fail':
  3286. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3287. return "fail"
  3288. # Check units and convert if necessary
  3289. # This condition CAN be true because initialize() can change obj.units
  3290. if self.options["units"].upper() != obj.units.upper():
  3291. self.inform.emit('%s: %s' %
  3292. (_("Converting units to "), self.options["units"]))
  3293. obj.convert_units(self.options["units"])
  3294. t3 = time.time()
  3295. self.log.debug("%f seconds converting units." % (t3 - t2))
  3296. # Create the bounding box for the object and then add the results to the obj.options
  3297. try:
  3298. xmin, ymin, xmax, ymax = obj.bounds()
  3299. obj.options['xmin'] = xmin
  3300. obj.options['ymin'] = ymin
  3301. obj.options['xmax'] = xmax
  3302. obj.options['ymax'] = ymax
  3303. except Exception as e:
  3304. log.warning("The object has no bounds properties. %s" % str(e))
  3305. return "fail"
  3306. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3307. # Move the object to the main thread and let the app know that it is available.
  3308. obj.moveToThread(self.main_thread)
  3309. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3310. return obj
  3311. def new_excellon_object(self):
  3312. """
  3313. Creates a new, blank Excellon object.
  3314. :return: None
  3315. """
  3316. self.report_usage("new_excellon_object()")
  3317. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3318. def new_geometry_object(self):
  3319. """
  3320. Creates a new, blank and single-tool Geometry object.
  3321. :return: None
  3322. """
  3323. self.report_usage("new_geometry_object()")
  3324. def initialize(obj, self):
  3325. obj.multitool = False
  3326. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3327. def new_gerber_object(self):
  3328. """
  3329. Creates a new, blank Gerber object.
  3330. :return: None
  3331. """
  3332. self.report_usage("new_gerber_object()")
  3333. def initialize(grb_obj, self):
  3334. grb_obj.multitool = False
  3335. grb_obj.source_file = []
  3336. grb_obj.multigeo = False
  3337. grb_obj.follow = False
  3338. grb_obj.apertures = {}
  3339. grb_obj.solid_geometry = []
  3340. try:
  3341. grb_obj.options['xmin'] = 0
  3342. grb_obj.options['ymin'] = 0
  3343. grb_obj.options['xmax'] = 0
  3344. grb_obj.options['ymax'] = 0
  3345. except KeyError:
  3346. pass
  3347. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3348. def on_object_created(self, obj, plot, autoselect):
  3349. """
  3350. Event callback for object creation.
  3351. It will add the new object to the collection. After that it will plot the object in a threaded way
  3352. :param obj: The newly created FlatCAM object.
  3353. :param plot: if the newly create object t obe plotted
  3354. :param autoselect: if the newly created object to be autoselected after creation
  3355. :return: None
  3356. """
  3357. t0 = time.time() # DEBUG
  3358. self.log.debug("on_object_created()")
  3359. # The Collection might change the name if there is a collision
  3360. self.collection.append(obj)
  3361. # after adding the object to the collection always update the list of objects that are in the collection
  3362. self.all_objects_list = self.collection.get_list()
  3363. # self.inform.emit('[selected] %s created & selected: %s' %
  3364. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3365. if obj.kind == 'gerber':
  3366. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3367. kind=obj.kind.capitalize(), color='green', name=str(obj.options['name'])))
  3368. elif obj.kind == 'excellon':
  3369. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3370. kind=obj.kind.capitalize(), color='brown', name=str(obj.options['name'])))
  3371. elif obj.kind == 'cncjob':
  3372. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3373. kind=obj.kind.capitalize(), color='blue', name=str(obj.options['name'])))
  3374. elif obj.kind == 'geometry':
  3375. self.inform.emit(_('[selected] {kind} created/selected: <span style="color:{color};">{name}</span>').format(
  3376. kind=obj.kind.capitalize(), color='red', name=str(obj.options['name'])))
  3377. # update the SHELL auto-completer model with the name of the new object
  3378. self.myKeywords.append(obj.options['name'])
  3379. self.shell._edit.set_model_data(self.myKeywords)
  3380. self.ui.code_editor.set_model_data(self.myKeywords)
  3381. if autoselect:
  3382. # select the just opened object but deselect the previous ones
  3383. self.collection.set_all_inactive()
  3384. self.collection.set_active(obj.options["name"])
  3385. else:
  3386. self.collection.set_all_inactive()
  3387. # here it is done the object plotting
  3388. def worker_task(t_obj):
  3389. with self.proc_container.new(_("Plotting")):
  3390. if isinstance(t_obj, FlatCAMCNCjob):
  3391. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3392. else:
  3393. t_obj.plot()
  3394. t1 = time.time() # DEBUG
  3395. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3396. self.object_plotted.emit(t_obj)
  3397. # Send to worker
  3398. # self.worker.add_task(worker_task, [self])
  3399. if plot is True:
  3400. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3401. def on_object_changed(self, obj):
  3402. """
  3403. Called whenever the geometry of the object was changed in some way.
  3404. This require the update of it's bounding values so it can be the selected on canvas.
  3405. Update the bounding box data from obj.options
  3406. :param obj: the object that was changed
  3407. :return: None
  3408. """
  3409. xmin, ymin, xmax, ymax = obj.bounds()
  3410. obj.options['xmin'] = xmin
  3411. obj.options['ymin'] = ymin
  3412. obj.options['xmax'] = xmax
  3413. obj.options['ymax'] = ymax
  3414. log.debug("Object changed, updating the bounding box data on self.options")
  3415. # delete the old selection shape
  3416. self.delete_selection_shape()
  3417. self.should_we_save = True
  3418. def on_object_plotted(self, obj):
  3419. """
  3420. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3421. :param obj: object to be fit into view
  3422. :return: None
  3423. """
  3424. self.on_zoom_fit(None)
  3425. def options_read_form(self):
  3426. """
  3427. Same as it's equivalent from the defaults.
  3428. self.options use to store the preferences per project. No longer used.
  3429. :return: None
  3430. """
  3431. for option in self.options_form_fields:
  3432. self.options[option] = self.options_form_fields[option].get_value()
  3433. def options_write_form(self):
  3434. """
  3435. Same as it's equivalent from the defaults.
  3436. self.options use to store the preferences per project. No longer used.
  3437. :return: None
  3438. """
  3439. for option in self.options:
  3440. self.options_write_form_field(option)
  3441. def options_write_form_field(self, field):
  3442. """
  3443. Same as it's equivalent from the defaults.
  3444. self.options use to store the preferences per project. No longer used.
  3445. :return: None
  3446. """
  3447. try:
  3448. self.options_form_fields[field].set_value(self.options[field])
  3449. except KeyError:
  3450. # Changed from error to debug. This allows to have data stored
  3451. # which is not user-editable.
  3452. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  3453. pass
  3454. def on_about(self):
  3455. """
  3456. Displays the "about" dialog found in the Menu --> Help.
  3457. :return: None
  3458. """
  3459. self.report_usage("on_about")
  3460. version = self.version
  3461. version_date = self.version_date
  3462. beta = self.beta
  3463. class AboutDialog(QtWidgets.QDialog):
  3464. def __init__(self, parent=None):
  3465. QtWidgets.QDialog.__init__(self, parent)
  3466. # Icon and title
  3467. self.setWindowIcon(parent.app_icon)
  3468. self.setWindowTitle(_("About FlatCAM"))
  3469. self.resize(600, 200)
  3470. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3471. # self.setStyleSheet(
  3472. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3473. # "background-attachment: fixed"
  3474. # )
  3475. # bgimage = QtGui.QImage('share/flatcam_icon256.png')
  3476. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3477. # palette = QtGui.QPalette()
  3478. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3479. # self.setPalette(palette)
  3480. logo = QtWidgets.QLabel()
  3481. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  3482. title = QtWidgets.QLabel(
  3483. "<font size=8><B>FlatCAM</B></font><BR>"
  3484. "{title}<BR>"
  3485. "<BR>"
  3486. "<BR>"
  3487. # "<B>{devel}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3488. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3489. # "<b>{down}</B> area &nbsp;&nbsp;&nbsp;&nbsp;"
  3490. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3491. # "<b> {issue}</B> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"
  3492. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3493. "<B>{issue}</B></a><BR>".format(
  3494. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3495. devel=_("Development"),
  3496. down=_("DOWNLOAD"),
  3497. issue=_("Issue tracker"))
  3498. )
  3499. title.setOpenExternalLinks(True)
  3500. closebtn = QtWidgets.QPushButton(_("Close"))
  3501. tab_widget = QtWidgets.QTabWidget()
  3502. description_label = QtWidgets.QLabel(
  3503. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3504. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3505. version=version,
  3506. beta=('BETA' if beta else ''),
  3507. date=version_date,
  3508. arch=platform.architecture()[0])
  3509. )
  3510. description_label.setOpenExternalLinks(True)
  3511. license_label = QtWidgets.QLabel(
  3512. _(
  3513. '(c) Copyright 2014 Juan Pablo Caram.\n\n'
  3514. 'Licensed under the MIT license:\n'
  3515. 'http://www.opensource.org/licenses/mit-license.php\n\n'
  3516. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3517. 'of this software and associated documentation files (the "Software"), to deal\n'
  3518. 'in the Software without restriction, including without limitation the rights\n'
  3519. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3520. 'copies of the Software, and to permit persons to whom the Software is\n'
  3521. ' furnished to do so, subject to the following conditions:\n\n'
  3522. 'The above copyright notice and this permission notice shall be included in\n'
  3523. 'all copies or substantial portions of the Software.\n\n'
  3524. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3525. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3526. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3527. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3528. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3529. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3530. 'THE SOFTWARE.'
  3531. )
  3532. )
  3533. license_label.setOpenExternalLinks(True)
  3534. # layouts
  3535. layout1 = QtWidgets.QVBoxLayout()
  3536. layout1_1 = QtWidgets.QHBoxLayout()
  3537. layout1_2 = QtWidgets.QHBoxLayout()
  3538. layout2 = QtWidgets.QHBoxLayout()
  3539. layout3 = QtWidgets.QHBoxLayout()
  3540. self.setLayout(layout1)
  3541. layout1.addLayout(layout1_1)
  3542. layout1.addLayout(layout1_2)
  3543. layout1.addLayout(layout2)
  3544. layout1.addLayout(layout3)
  3545. layout1_1.addStretch()
  3546. layout1_1.addWidget(description_label)
  3547. layout1_2.addWidget(tab_widget)
  3548. self.splash_tab = QtWidgets.QWidget()
  3549. self.splash_tab.setObjectName("splash_about")
  3550. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3551. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3552. tab_widget.addTab(self.splash_tab, _("Splash"))
  3553. self.programmmers_tab = QtWidgets.QWidget()
  3554. self.programmmers_tab.setObjectName("programmers_about")
  3555. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3556. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3557. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3558. self.translators_tab = QtWidgets.QWidget()
  3559. self.translators_tab.setObjectName("translators_about")
  3560. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3561. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3562. tab_widget.addTab(self.translators_tab, _("Translators"))
  3563. self.license_tab = QtWidgets.QWidget()
  3564. self.license_tab.setObjectName("license_about")
  3565. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3566. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3567. tab_widget.addTab(self.license_tab, _("License"))
  3568. self.splash_tab_layout.addWidget(logo, stretch=0)
  3569. self.splash_tab_layout.addWidget(title, stretch=1)
  3570. pal = QtGui.QPalette()
  3571. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3572. self.prog_form_lay = QtWidgets.QFormLayout()
  3573. self.prog_form_lay.setHorizontalSpacing(20)
  3574. prog_widget = QtWidgets.QWidget()
  3575. prog_widget.setLayout(self.prog_form_lay)
  3576. prog_scroll = QtWidgets.QScrollArea()
  3577. prog_scroll.setWidget(prog_widget)
  3578. prog_scroll.setWidgetResizable(True)
  3579. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3580. prog_scroll.setPalette(pal)
  3581. self.programmmers_tab_layout.addWidget(prog_scroll)
  3582. self.prog_form_lay.addRow(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")),
  3583. QtWidgets.QLabel('<b>%s</b>' % _("Status")))
  3584. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Juan Pablo Caram"),
  3585. QtWidgets.QLabel('%s' % _("Program Author")))
  3586. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Denis Hayrullin"))
  3587. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Kamil Sopko"))
  3588. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marius Stanciu"),
  3589. QtWidgets.QLabel('%s' % _("Maintainer >=2019")))
  3590. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3591. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Alexandru Lazar"))
  3592. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Matthieu Berthomé"))
  3593. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Evans"))
  3594. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Victor Benso"))
  3595. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3596. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Barnaby Walters"))
  3597. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"))
  3598. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lei Zheng"))
  3599. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Marco A Quezada"))
  3600. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3601. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Cedric Dussud"))
  3602. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Chris Hemingway"))
  3603. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Damian Wrobel"))
  3604. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Daniel Sallin"))
  3605. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3606. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Bruno Vunderl"))
  3607. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Gonzalo Lopez"))
  3608. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Jakob Staudt"))
  3609. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Mike Smith"))
  3610. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3611. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Lubos Medovarsky"))
  3612. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Steve Martina"))
  3613. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "Thomas Duffin"))
  3614. self.prog_form_lay.addRow(QtWidgets.QLabel(''))
  3615. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Idechix"))
  3616. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@SM"))
  3617. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@grbf"))
  3618. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@Symonty"))
  3619. self.prog_form_lay.addRow(QtWidgets.QLabel('%s' % "@mgix"))
  3620. self.translator_grid_lay = QtWidgets.QGridLayout()
  3621. # trans_widget = QtWidgets.QWidget()
  3622. # trans_widget.setLayout(self.translator_grid_lay)
  3623. # self.translators_tab_layout.addWidget(trans_widget)
  3624. # self.translators_tab_layout.addStretch()
  3625. trans_widget = QtWidgets.QWidget()
  3626. trans_widget.setLayout(self.translator_grid_lay)
  3627. trans_scroll = QtWidgets.QScrollArea()
  3628. trans_scroll.setWidget(trans_widget)
  3629. trans_scroll.setWidgetResizable(True)
  3630. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3631. trans_scroll.setPalette(pal)
  3632. self.translators_tab_layout.addWidget(trans_scroll)
  3633. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  3634. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  3635. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3636. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Brasilian - Portuguese"), 1, 0)
  3637. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  3638. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 1, 2)
  3639. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 2, 0)
  3640. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 2, 1)
  3641. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 2)
  3642. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 3, 0)
  3643. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 3, 1)
  3644. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  3645. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 4, 0)
  3646. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 4, 1)
  3647. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 4, 2)
  3648. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 5, 0)
  3649. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Translation)"), 5, 1)
  3650. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 2)
  3651. self.translator_grid_lay.setColumnStretch(0, 0)
  3652. self.translators_tab_layout.addStretch()
  3653. self.license_tab_layout.addWidget(license_label)
  3654. self.license_tab_layout.addStretch()
  3655. layout3.addStretch()
  3656. layout3.addWidget(closebtn)
  3657. closebtn.clicked.connect(self.accept)
  3658. AboutDialog(self.ui).exec_()
  3659. def on_file_savedefaults(self):
  3660. """
  3661. Callback for menu item File->Save Defaults. Saves application default options
  3662. ``self.defaults`` to current_defaults.FlatConfig.
  3663. :return: None
  3664. """
  3665. self.save_defaults()
  3666. # def on_app_exit(self):
  3667. # self.report_usage("on_app_exit()")
  3668. #
  3669. # if self.collection.get_list():
  3670. # msgbox = QtWidgets.QMessageBox()
  3671. # # msgbox.setText("<B>Save changes ...</B>")
  3672. # msgbox.setText("There are files/objects opened in FlatCAM. "
  3673. # "\n"
  3674. # "Do you want to Save the project?")
  3675. # msgbox.setWindowTitle("Save changes")
  3676. # msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3677. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  3678. # QtWidgets.QMessageBox.Cancel)
  3679. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  3680. #
  3681. # response = msgbox.exec_()
  3682. #
  3683. # if response == QtWidgets.QMessageBox.Yes:
  3684. # self.on_file_saveprojectas(thread=False)
  3685. # elif response == QtWidgets.QMessageBox.Cancel:
  3686. # return
  3687. # self.save_defaults()
  3688. # else:
  3689. # self.save_defaults()
  3690. # log.debug("Application defaults saved ... Exit event.")
  3691. # QtWidgets.qApp.quit()
  3692. def save_defaults(self, silent=False, data_path=None, first_time=False):
  3693. """
  3694. Saves application default options
  3695. ``self.defaults`` to current_defaults.FlatConfig file.
  3696. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  3697. used at the next launch of the application.
  3698. :param silent: whether to display a message in status bar or not; boolean
  3699. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  3700. When the application is portable it should be a mobile location.
  3701. :return: None
  3702. """
  3703. self.report_usage("save_defaults")
  3704. if data_path is None:
  3705. data_path = self.data_path
  3706. # Read options from file
  3707. try:
  3708. f = open(data_path + "/current_defaults.FlatConfig")
  3709. defaults_file_content = f.read()
  3710. f.close()
  3711. except:
  3712. e = sys.exc_info()[0]
  3713. App.log.error("Could not load defaults file.")
  3714. App.log.error(str(e))
  3715. self.inform.emit('[ERROR_NOTCL] %s' %
  3716. _("Could not load defaults file."))
  3717. return
  3718. try:
  3719. defaults = json.loads(defaults_file_content)
  3720. except:
  3721. e = sys.exc_info()[0]
  3722. App.log.error("Failed to parse defaults file.")
  3723. App.log.error(str(e))
  3724. self.inform.emit('[ERROR_NOTCL] %s' %
  3725. _("Failed to parse defaults file."))
  3726. return
  3727. # Update options
  3728. self.defaults_read_form()
  3729. defaults.update(self.defaults)
  3730. self.propagate_defaults(silent=True)
  3731. # Save the toolbar view
  3732. tb_status = 0
  3733. if self.ui.toolbarfile.isVisible():
  3734. tb_status += 1
  3735. if self.ui.toolbargeo.isVisible():
  3736. tb_status += 2
  3737. if self.ui.toolbarview.isVisible():
  3738. tb_status += 4
  3739. if self.ui.toolbartools.isVisible():
  3740. tb_status += 8
  3741. if self.ui.exc_edit_toolbar.isVisible():
  3742. tb_status += 16
  3743. if self.ui.geo_edit_toolbar.isVisible():
  3744. tb_status += 32
  3745. if self.ui.grb_edit_toolbar.isVisible():
  3746. tb_status += 64
  3747. if self.ui.snap_toolbar.isVisible():
  3748. tb_status += 128
  3749. if self.ui.toolbarshell.isVisible():
  3750. tb_status += 256
  3751. if first_time is False:
  3752. self.defaults["global_toolbar_view"] = tb_status
  3753. # Save update options
  3754. try:
  3755. f = open(data_path + "/current_defaults.FlatConfig", "w")
  3756. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  3757. f.close()
  3758. except:
  3759. self.inform.emit('[ERROR_NOTCL] %s' %
  3760. _("Failed to write defaults to file."))
  3761. return
  3762. if not silent:
  3763. self.inform.emit('[success] %s' %
  3764. _("Preferences saved."))
  3765. def save_factory_defaults(self, silent=False, data_path=None):
  3766. """
  3767. Saves application factory default options
  3768. ``self.defaults`` to factory_defaults.FlatConfig.
  3769. It's a one time job done just after the first install.
  3770. :param silent: whether to display a message in status bar or not; boolean
  3771. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  3772. When the application is portable it should be a mobile location.
  3773. :return: None
  3774. """
  3775. self.report_usage("save_factory_defaults")
  3776. if data_path is None:
  3777. data_path = self.data_path
  3778. # Read options from file
  3779. try:
  3780. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  3781. factory_defaults_file_content = f_f_def.read()
  3782. f_f_def.close()
  3783. except:
  3784. e = sys.exc_info()[0]
  3785. App.log.error("Could not load factory defaults file.")
  3786. App.log.error(str(e))
  3787. self.inform.emit('[ERROR_NOTCL] %s' %
  3788. _("Could not load factory defaults file."))
  3789. return
  3790. try:
  3791. factory_defaults = json.loads(factory_defaults_file_content)
  3792. except:
  3793. e = sys.exc_info()[0]
  3794. App.log.error("Failed to parse factory defaults file.")
  3795. App.log.error(str(e))
  3796. self.inform.emit('[ERROR_NOTCL] %s' %
  3797. _("Failed to parse factory defaults file."))
  3798. return
  3799. # Update options
  3800. self.defaults_read_form()
  3801. factory_defaults.update(self.defaults)
  3802. self.propagate_defaults(silent=True)
  3803. # Save update options
  3804. try:
  3805. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  3806. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3807. f_f_def_s.close()
  3808. except:
  3809. self.inform.emit('[ERROR_NOTCL] %s' %
  3810. _("Failed to write factory defaults to file."))
  3811. return
  3812. if silent is False:
  3813. self.inform.emit(_("Factory defaults saved."))
  3814. def final_save(self):
  3815. """
  3816. Callback for doing a preferences save to file whenever the application is about to quit.
  3817. If the project has changes, it will ask the user to save the project.
  3818. :return: None
  3819. """
  3820. if self.save_in_progress:
  3821. self.inform.emit('[WARNING_NOTCL] %s' %
  3822. _("Application is saving the project. Please wait ..."))
  3823. return
  3824. if self.should_we_save and self.collection.get_list():
  3825. msgbox = QtWidgets.QMessageBox()
  3826. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  3827. "\n"
  3828. "Do you want to Save the project?"))
  3829. msgbox.setWindowTitle(_("Save changes"))
  3830. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  3831. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  3832. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  3833. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3834. msgbox.setDefaultButton(bt_yes)
  3835. msgbox.exec_()
  3836. response = msgbox.clickedButton()
  3837. if response == bt_yes:
  3838. try:
  3839. self.trayIcon.hide()
  3840. except:
  3841. pass
  3842. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  3843. elif response == bt_no:
  3844. try:
  3845. self.trayIcon.hide()
  3846. except:
  3847. pass
  3848. self.quit_application()
  3849. elif response == bt_cancel:
  3850. return
  3851. else:
  3852. try:
  3853. self.trayIcon.hide()
  3854. except:
  3855. pass
  3856. self.quit_application()
  3857. def quit_application(self):
  3858. """
  3859. Called (as a pyslot or not) when the application is quit.
  3860. :return: None
  3861. """
  3862. self.save_defaults()
  3863. log.debug("App.final_save() --> App Defaults saved.")
  3864. if self.cmd_line_headless != 1:
  3865. # save app state to file
  3866. settings = QSettings("Open Source", "FlatCAM")
  3867. settings.setValue('saved_gui_state', self.ui.saveState())
  3868. settings.setValue('maximized_gui', self.ui.isMaximized())
  3869. settings.setValue('language', self.ui.general_defaults_form.general_app_group.language_cb.get_value())
  3870. settings.setValue(
  3871. 'notebook_font_size',
  3872. self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  3873. )
  3874. settings.setValue('axis_font_size',
  3875. self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value())
  3876. settings.setValue(
  3877. 'textbox_font_size',
  3878. self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  3879. )
  3880. settings.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  3881. # This will write the setting to the platform specific storage.
  3882. del settings
  3883. log.debug("App.final_save() --> App UI state saved.")
  3884. QtWidgets.qApp.quit()
  3885. def on_portable_checked(self, state):
  3886. """
  3887. Callback called when the checkbox in Preferences GUI is checked.
  3888. It will set the application as portable by creating the preferences and recent files in the
  3889. 'config' folder found in the FlatCAM installation folder.
  3890. :param state: boolean, the state of the checkbox when clicked/checked
  3891. :return:
  3892. """
  3893. line_no = 0
  3894. data = None
  3895. if sys.platform != 'win32':
  3896. # this won't work in Linux or MacOS
  3897. return
  3898. # test if the app was frozen and choose the path for the configuration file
  3899. if getattr(sys, "frozen", False) is True:
  3900. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3901. else:
  3902. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3903. config_file = current_data_path + '\\configuration.txt'
  3904. try:
  3905. with open(config_file, 'r') as f:
  3906. try:
  3907. data = f.readlines()
  3908. except Exception as e:
  3909. log.debug('App.__init__() -->%s' % str(e))
  3910. return
  3911. except FileNotFoundError:
  3912. pass
  3913. for line in data:
  3914. line = line.strip('\n')
  3915. param = str(line).rpartition('=')
  3916. if param[0] == 'portable':
  3917. break
  3918. line_no += 1
  3919. if state:
  3920. data[line_no] = 'portable=True\n'
  3921. # create the new defauults files
  3922. # create current_defaults.FlatConfig file if there is none
  3923. try:
  3924. f = open(current_data_path + '/current_defaults.FlatConfig')
  3925. f.close()
  3926. except IOError:
  3927. App.log.debug('Creating empty current_defaults.FlatConfig')
  3928. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3929. json.dump({}, f)
  3930. f.close()
  3931. # create factory_defaults.FlatConfig file if there is none
  3932. try:
  3933. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3934. f.close()
  3935. except IOError:
  3936. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3937. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3938. json.dump({}, f)
  3939. f.close()
  3940. try:
  3941. f = open(current_data_path + '/recent.json')
  3942. f.close()
  3943. except IOError:
  3944. App.log.debug('Creating empty recent.json')
  3945. f = open(current_data_path + '/recent.json', 'w')
  3946. json.dump([], f)
  3947. f.close()
  3948. try:
  3949. fp = open(current_data_path + '/recent_projects.json')
  3950. fp.close()
  3951. except IOError:
  3952. App.log.debug('Creating empty recent_projects.json')
  3953. fp = open(current_data_path + '/recent_projects.json', 'w')
  3954. json.dump([], fp)
  3955. fp.close()
  3956. # save the current defaults to the new defaults file
  3957. self.save_defaults(silent=True, data_path=current_data_path)
  3958. self.save_factory_defaults(silent=True, data_path=current_data_path)
  3959. else:
  3960. data[line_no] = 'portable=False\n'
  3961. with open(config_file, 'w') as f:
  3962. f.writelines(data)
  3963. def on_toggle_shell(self):
  3964. """
  3965. Toggle shell: if is visible close it, if it is closed then open it
  3966. :return:
  3967. """
  3968. self.report_usage("on_toggle_shell()")
  3969. if self.ui.shell_dock.isVisible():
  3970. self.ui.shell_dock.hide()
  3971. else:
  3972. self.ui.shell_dock.show()
  3973. def on_register_files(self, obj_type=None):
  3974. """
  3975. Called whenever there is a need to register file extensions with FlatCAM.
  3976. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3977. :param obj_type: the type of object to be register for.
  3978. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3979. :return: None
  3980. """
  3981. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3982. new_reg_path = 'Software\\Classes\\'
  3983. # find if the current user is admin
  3984. try:
  3985. is_admin = os.getuid() == 0
  3986. except AttributeError:
  3987. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3988. if is_admin is True:
  3989. root_path = winreg.HKEY_LOCAL_MACHINE
  3990. else:
  3991. root_path = winreg.HKEY_CURRENT_USER
  3992. # create the keys
  3993. def set_reg(name, root_path, new_reg_path, value):
  3994. try:
  3995. winreg.CreateKey(root_path, new_reg_path)
  3996. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3997. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3998. return True
  3999. except WindowsError:
  4000. return False
  4001. # delete key in registry
  4002. def delete_reg(root_path, reg_path, key_to_del):
  4003. key_to_del_path = reg_path + key_to_del
  4004. try:
  4005. winreg.DeleteKey(root_path, key_to_del_path)
  4006. return True
  4007. except WindowsError:
  4008. return False
  4009. if obj_type is None or obj_type == 'excellon':
  4010. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4011. exc_list = [x for x in exc_list if x != '']
  4012. # register all keys in the Preferences window
  4013. for ext in exc_list:
  4014. new_k = new_reg_path + '.%s' % ext
  4015. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4016. # and unregister those that are no longer in the Preferences windows but are in the file
  4017. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4018. if ext not in exc_list:
  4019. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4020. # now write the updated extensions to the self.defaults
  4021. # new_ext = ''
  4022. # for ext in exc_list:
  4023. # new_ext = new_ext + ext + ', '
  4024. # self.defaults["fa_excellon"] = new_ext
  4025. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4026. if obj_type is None or obj_type == 'gcode':
  4027. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4028. gco_list = [x for x in gco_list if x != '']
  4029. # register all keys in the Preferences window
  4030. for ext in gco_list:
  4031. new_k = new_reg_path + '.%s' % ext
  4032. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4033. # and unregister those that are no longer in the Preferences windows but are in the file
  4034. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4035. if ext not in gco_list:
  4036. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4037. # now write the updated extensions to the self.defaults
  4038. # new_ext = ''
  4039. # for ext in gco_list:
  4040. # new_ext = new_ext + ext + ', '
  4041. # self.defaults["fa_gcode"] = new_ext
  4042. self.inform.emit('[success] %s' %
  4043. _("Selected GCode file extensions registered with FlatCAM."))
  4044. if obj_type is None or obj_type == 'gerber':
  4045. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4046. grb_list = [x for x in grb_list if x != '']
  4047. # register all keys in the Preferences window
  4048. for ext in grb_list:
  4049. new_k = new_reg_path + '.%s' % ext
  4050. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4051. # and unregister those that are no longer in the Preferences windows but are in the file
  4052. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4053. if ext not in grb_list:
  4054. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4055. # now write the updated extensions to the self.defaults
  4056. # new_ext = ''
  4057. # for ext in grb_list:
  4058. # new_ext = new_ext + ext + ', '
  4059. # self.defaults["fa_gerber"] = new_ext
  4060. self.inform.emit('[success] %s' %
  4061. _("Selected Gerber file extensions registered with FlatCAM."))
  4062. def add_extension(self, ext_type):
  4063. if ext_type == 'excellon':
  4064. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4065. if new_ext == '':
  4066. return
  4067. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4068. if new_ext in old_val:
  4069. return
  4070. old_val.append(new_ext)
  4071. old_val.sort()
  4072. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4073. if ext_type == 'gcode':
  4074. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4075. if new_ext == '':
  4076. return
  4077. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4078. if new_ext in old_val:
  4079. return
  4080. old_val.append(new_ext)
  4081. old_val.sort()
  4082. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4083. if ext_type == 'gerber':
  4084. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4085. if new_ext == '':
  4086. return
  4087. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4088. if new_ext in old_val:
  4089. return
  4090. old_val.append(new_ext)
  4091. old_val.sort()
  4092. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4093. if ext_type == 'keyword':
  4094. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4095. if new_kw == '':
  4096. return
  4097. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4098. if new_kw in old_val:
  4099. return
  4100. old_val.append(new_kw)
  4101. old_val.sort()
  4102. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4103. # update the self.myKeywords so the model is updated
  4104. self.autocomplete_kw_list = \
  4105. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4106. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4107. self.shell._edit.set_model_data(self.myKeywords)
  4108. self.ui.code_editor.set_model_data(self.myKeywords)
  4109. def del_extension(self, ext_type):
  4110. if ext_type == 'excellon':
  4111. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4112. if new_ext == '':
  4113. return
  4114. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4115. if new_ext not in old_val:
  4116. return
  4117. old_val.remove(new_ext)
  4118. old_val.sort()
  4119. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4120. if ext_type == 'gcode':
  4121. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4122. if new_ext == '':
  4123. return
  4124. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4125. if new_ext not in old_val:
  4126. return
  4127. old_val.remove(new_ext)
  4128. old_val.sort()
  4129. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4130. if ext_type == 'gerber':
  4131. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4132. if new_ext == '':
  4133. return
  4134. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4135. if new_ext not in old_val:
  4136. return
  4137. old_val.remove(new_ext)
  4138. old_val.sort()
  4139. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4140. if ext_type == 'keyword':
  4141. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4142. if new_kw == '':
  4143. return
  4144. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4145. if new_kw not in old_val:
  4146. return
  4147. old_val.remove(new_kw)
  4148. old_val.sort()
  4149. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4150. # update the self.myKeywords so the model is updated
  4151. self.autocomplete_kw_list = \
  4152. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4153. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4154. self.shell._edit.set_model_data(self.myKeywords)
  4155. self.ui.code_editor.set_model_data(self.myKeywords)
  4156. def restore_extensions(self, ext_type):
  4157. if ext_type == 'excellon':
  4158. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4159. # for the ability to open Excellon files with .txt extension
  4160. new_exc_list = deepcopy(self.exc_list)
  4161. try:
  4162. new_exc_list.remove('txt')
  4163. except ValueError:
  4164. pass
  4165. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4166. if ext_type == 'gcode':
  4167. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4168. if ext_type == 'gerber':
  4169. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4170. if ext_type == 'keyword':
  4171. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4172. # update the self.myKeywords so the model is updated
  4173. self.autocomplete_kw_list = self.default_keywords
  4174. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4175. self.shell._edit.set_model_data(self.myKeywords)
  4176. self.ui.code_editor.set_model_data(self.myKeywords)
  4177. def delete_all_extensions(self, ext_type):
  4178. if ext_type == 'excellon':
  4179. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4180. if ext_type == 'gcode':
  4181. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4182. if ext_type == 'gerber':
  4183. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4184. if ext_type == 'keyword':
  4185. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4186. # update the self.myKeywords so the model is updated
  4187. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4188. self.shell._edit.set_model_data(self.myKeywords)
  4189. self.ui.code_editor.set_model_data(self.myKeywords)
  4190. def on_edit_join(self, name=None):
  4191. """
  4192. Callback for Edit->Join. Joins the selected geometry objects into
  4193. a new one.
  4194. :return: None
  4195. """
  4196. self.report_usage("on_edit_join()")
  4197. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4198. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4199. tooldias = []
  4200. geo_type_list = set()
  4201. objs = self.collection.get_selected()
  4202. if len(objs) < 2:
  4203. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4204. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4205. return 'fail'
  4206. for obj in objs:
  4207. geo_type_list.add(obj.multigeo)
  4208. # if len(geo_type_list) == 1 means that all list elements are the same
  4209. if len(geo_type_list) != 1:
  4210. self.inform.emit('[ERROR] %s' %
  4211. _("Failed join. The Geometry objects are of different types.\n"
  4212. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4213. "convert from one to another and retry joining \n"
  4214. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4215. "the result may not be what was expected. \n"
  4216. "Check the generated GCODE."))
  4217. return
  4218. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4219. if True in geo_type_list:
  4220. def initialize(obj, app):
  4221. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=True)
  4222. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4223. for v in obj.tools.values():
  4224. v['data']['name'] = obj_name_multi
  4225. self.new_object("geometry", obj_name_multi, initialize)
  4226. else:
  4227. def initialize(obj, app):
  4228. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=obj, multigeo=False)
  4229. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4230. for v in obj.tools.values():
  4231. v['data']['name'] = obj_name_single
  4232. self.new_object("geometry", obj_name_single, initialize)
  4233. self.should_we_save = True
  4234. def on_edit_join_exc(self):
  4235. """
  4236. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4237. a new Excellon.
  4238. :return: None
  4239. """
  4240. self.report_usage("on_edit_join_exc()")
  4241. objs = self.collection.get_selected()
  4242. for obj in objs:
  4243. if not isinstance(obj, FlatCAMExcellon):
  4244. self.inform.emit('[ERROR_NOTCL] %s' %
  4245. _("Failed. Excellon joining works only on Excellon objects."))
  4246. return
  4247. if len(objs) < 2:
  4248. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4249. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4250. return 'fail'
  4251. def initialize(obj, app):
  4252. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=obj)
  4253. self.new_object("excellon", 'Combo_Excellon', initialize)
  4254. self.should_we_save = True
  4255. def on_edit_join_grb(self):
  4256. """
  4257. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4258. a new Gerber object.
  4259. :return: None
  4260. """
  4261. self.report_usage("on_edit_join_grb()")
  4262. objs = self.collection.get_selected()
  4263. for obj in objs:
  4264. if not isinstance(obj, FlatCAMGerber):
  4265. self.inform.emit('[ERROR_NOTCL] %s' %
  4266. _("Failed. Gerber joining works only on Gerber objects."))
  4267. return
  4268. if len(objs) < 2:
  4269. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4270. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4271. return 'fail'
  4272. def initialize(obj, app):
  4273. FlatCAMGerber.merge(self, grb_list=objs, grb_final=obj)
  4274. self.new_object("gerber", 'Combo_Gerber', initialize)
  4275. self.should_we_save = True
  4276. def on_convert_singlegeo_to_multigeo(self):
  4277. """
  4278. Called for converting a Geometry object from single-geo to multi-geo.
  4279. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4280. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4281. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4282. the solid-geometry of that tool.
  4283. :return: None
  4284. """
  4285. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4286. obj = self.collection.get_active()
  4287. if obj is None:
  4288. self.inform.emit('[ERROR_NOTCL] %s' %
  4289. _("Failed. Select a Geometry Object and try again."))
  4290. return
  4291. if not isinstance(obj, FlatCAMGeometry):
  4292. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4293. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4294. return
  4295. obj.multigeo = True
  4296. for tooluid, dict_value in obj.tools.items():
  4297. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4298. if not isinstance(obj.solid_geometry, list):
  4299. obj.solid_geometry = [obj.solid_geometry]
  4300. obj.solid_geometry[:] = []
  4301. obj.plot()
  4302. self.should_we_save = True
  4303. self.inform.emit('[success] %s' %
  4304. _("A Geometry object was converted to MultiGeo type."))
  4305. def on_convert_multigeo_to_singlegeo(self):
  4306. """
  4307. Called for converting a Geometry object from multi-geo to single-geo.
  4308. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4309. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4310. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4311. the solid-geometry of that tool.
  4312. :return: None
  4313. """
  4314. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4315. obj = self.collection.get_active()
  4316. if obj is None:
  4317. self.inform.emit('[ERROR_NOTCL] %s' %
  4318. _("Failed. Select a Geometry Object and try again."))
  4319. return
  4320. if not isinstance(obj, FlatCAMGeometry):
  4321. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4322. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4323. return
  4324. obj.multigeo = False
  4325. total_solid_geometry = []
  4326. for tooluid, dict_value in obj.tools.items():
  4327. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4328. # clear the original geometry
  4329. dict_value['solid_geometry'][:] = []
  4330. obj.solid_geometry = deepcopy(total_solid_geometry)
  4331. obj.plot()
  4332. self.should_we_save = True
  4333. self.inform.emit('[success] %s' %
  4334. _("A Geometry object was converted to SingleGeo type."))
  4335. def on_options_dict_change(self, field):
  4336. """
  4337. Called whenever a key changed in the self.options dictionary. This dict was used to store the preferences of the
  4338. current project. This feature is no longer used.
  4339. :param field:
  4340. :return:
  4341. """
  4342. self.options_write_form_field(field)
  4343. if field == "units":
  4344. self.set_screen_units(self.options['units'])
  4345. def on_defaults_dict_change(self, field):
  4346. """
  4347. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4348. Edit -> Preferences tab window.
  4349. :param field: the key of the self.defaults dictionary that was changed.
  4350. :return: None
  4351. """
  4352. self.defaults_write_form_field(field)
  4353. if field == "units":
  4354. self.set_screen_units(self.defaults['units'])
  4355. def set_screen_units(self, units):
  4356. """
  4357. Set the FlatCAM units on the status bar.
  4358. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4359. :return: None
  4360. """
  4361. self.ui.units_label.setText("[" + units.lower() + "]")
  4362. def on_toggle_units(self, no_pref=False):
  4363. """
  4364. Callback for the Units radio-button change in the Preferences tab.
  4365. Changes the application's default units adn for the project too.
  4366. If changing the project's units, the change propagates to all of
  4367. the objects in the project.
  4368. :return: None
  4369. """
  4370. self.report_usage("on_toggle_units")
  4371. if self.toggle_units_ignore:
  4372. return
  4373. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4374. # If option is the same, then ignore
  4375. if new_units == self.defaults["units"].upper():
  4376. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4377. return
  4378. # Options to scale
  4379. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  4380. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4381. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4382. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4383. "excellon_z_pdepth",
  4384. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4385. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4386. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4387. "geometry_feedrate_probe",
  4388. 'cncjob_tooldia',
  4389. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4390. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia"
  4391. "tools_2sided_drilldia", "tools_film_boundary",
  4392. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4393. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4394. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4395. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4396. "tools_transform_offset_y",
  4397. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4398. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4399. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4400. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4401. 'global_gridx', 'global_gridy', 'global_snap_max']
  4402. def scale_options(sfactor):
  4403. for dim in dimensions:
  4404. if dim == 'excellon_toolchangexy':
  4405. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4406. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4407. coords_xy[0] *= sfactor
  4408. coords_xy[1] *= sfactor
  4409. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4410. elif dim == 'geometry_toolchangexy':
  4411. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4412. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4413. coords_xy[0] *= sfactor
  4414. coords_xy[1] *= sfactor
  4415. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  4416. elif dim == 'geometry_cnctooldia':
  4417. tools_diameters = []
  4418. try:
  4419. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4420. tools_diameters = [eval(a) for a in tools_string if a != '']
  4421. except Exception as e:
  4422. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4423. self.options['geometry_cnctooldia'] = ''
  4424. for t in range(len(tools_diameters)):
  4425. tools_diameters[t] *= sfactor
  4426. self.options['geometry_cnctooldia'] += "%f," % tools_diameters[t]
  4427. elif dim == 'tools_ncctools':
  4428. ncctools = []
  4429. try:
  4430. tools_string = self.defaults["tools_ncctools"].split(",")
  4431. ncctools = [eval(a) for a in tools_string if a != '']
  4432. except Exception as e:
  4433. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4434. self.options['tools_ncctools'] = ''
  4435. for t in range(len(ncctools)):
  4436. ncctools[t] *= sfactor
  4437. self.options['tools_ncctools'] += "%f," % ncctools[t]
  4438. elif dim == 'tools_solderpaste_tools':
  4439. sptools = []
  4440. try:
  4441. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4442. sptools = [eval(a) for a in tools_string if a != '']
  4443. except Exception as e:
  4444. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4445. self.options['tools_solderpaste_tools'] = ""
  4446. for t in range(len(sptools)):
  4447. sptools[t] *= sfactor
  4448. self.options['tools_solderpaste_tools'] += "%f," % sptools[t]
  4449. elif dim == 'tools_solderpaste_xy_toolchange':
  4450. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4451. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4452. sp_coords[0] *= sfactor
  4453. sp_coords[1] *= sfactor
  4454. self.options['tools_solderpaste_xy_toolchange'] = "%f, %f" % (sp_coords[0], sp_coords[1])
  4455. elif dim == 'global_gridx' or dim == 'global_gridy':
  4456. if new_units == 'IN':
  4457. val = 0.1
  4458. try:
  4459. val = float(self.defaults[dim]) * sfactor
  4460. except Exception as e:
  4461. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4462. self.options[dim] = float('%.6f' % val)
  4463. else:
  4464. val = 0.1
  4465. try:
  4466. val = float(self.defaults[dim]) * sfactor
  4467. except Exception as e:
  4468. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4469. self.options[dim] = float('%.4f' % val)
  4470. else:
  4471. val = 0.1
  4472. try:
  4473. val = float(self.options[dim]) * sfactor
  4474. except Exception as e:
  4475. log.debug('App.on_toggle_units().scale_options() --> %s' % str(e))
  4476. self.options[dim] = val
  4477. def scale_defaults(sfactor):
  4478. for dim in dimensions:
  4479. if dim == 'excellon_toolchangexy':
  4480. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4481. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4482. coords_xy[0] *= sfactor
  4483. coords_xy[1] *= sfactor
  4484. self.defaults['excellon_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4485. elif dim == 'geometry_toolchangexy':
  4486. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4487. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4488. coords_xy[0] *= sfactor
  4489. coords_xy[1] *= sfactor
  4490. self.defaults['geometry_toolchangexy'] = "%.4f, %.4f" % (coords_xy[0], coords_xy[1])
  4491. elif dim == 'geometry_cnctooldia':
  4492. tools_diameters = []
  4493. try:
  4494. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4495. tools_diameters = [eval(a) for a in tools_string if a != '']
  4496. except Exception as e:
  4497. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4498. self.defaults['geometry_cnctooldia'] = ''
  4499. for t in range(len(tools_diameters)):
  4500. tools_diameters[t] *= sfactor
  4501. self.defaults['geometry_cnctooldia'] += "%.4f," % tools_diameters[t]
  4502. elif dim == 'tools_ncctools':
  4503. ncctools = []
  4504. try:
  4505. tools_string = self.defaults["tools_ncctools"].split(",")
  4506. ncctools = [eval(a) for a in tools_string if a != '']
  4507. except Exception as e:
  4508. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4509. self.defaults['tools_ncctools'] = ''
  4510. for t in range(len(ncctools)):
  4511. ncctools[t] *= sfactor
  4512. self.defaults['tools_ncctools'] += "%.4f," % ncctools[t]
  4513. elif dim == 'tools_solderpaste_tools':
  4514. sptools = []
  4515. try:
  4516. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  4517. sptools = [eval(a) for a in tools_string if a != '']
  4518. except Exception as e:
  4519. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4520. self.defaults['tools_solderpaste_tools'] = ""
  4521. for t in range(len(sptools)):
  4522. sptools[t] *= sfactor
  4523. self.defaults['tools_solderpaste_tools'] += "%.4f," % sptools[t]
  4524. elif dim == 'tools_solderpaste_xy_toolchange':
  4525. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  4526. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  4527. sp_coords[0] *= sfactor
  4528. sp_coords[1] *= sfactor
  4529. self.defaults['tools_solderpaste_xy_toolchange'] = "%.4f, %.4f" % (sp_coords[0], sp_coords[1])
  4530. elif dim == 'global_gridx' or dim == 'global_gridy':
  4531. if new_units == 'IN':
  4532. val = 0.1
  4533. try:
  4534. val = float(self.defaults[dim]) * sfactor
  4535. except Exception as e:
  4536. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4537. self.defaults[dim] = float('%.6f' % val)
  4538. else:
  4539. val = 0.1
  4540. try:
  4541. val = float(self.defaults[dim]) * sfactor
  4542. except Exception as e:
  4543. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4544. self.defaults[dim] = float('%.4f' % val)
  4545. else:
  4546. val = 0.1
  4547. try:
  4548. val = float(self.defaults[dim]) * sfactor
  4549. except Exception as e:
  4550. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  4551. self.defaults[dim] = val
  4552. # The scaling factor depending on choice of units.
  4553. factor = 1/25.4
  4554. if new_units == 'MM':
  4555. factor = 25.4
  4556. # Changing project units. Warn user.
  4557. msgbox = QtWidgets.QMessageBox()
  4558. msgbox.setWindowTitle(_("Toggle Units"))
  4559. msgbox.setWindowIcon(QtGui.QIcon('share/toggle_units32.png'))
  4560. msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4561. msgbox.setInformativeText(_("Changing the units of the project causes all geometrical "
  4562. "properties of all objects to be scaled accordingly.\nContinue?"))
  4563. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4564. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4565. msgbox.setDefaultButton(bt_ok)
  4566. msgbox.exec_()
  4567. response = msgbox.clickedButton()
  4568. if response == bt_ok:
  4569. if no_pref is False:
  4570. self.options_read_form()
  4571. scale_options(factor)
  4572. self.options_write_form()
  4573. self.defaults_read_form()
  4574. scale_defaults(factor)
  4575. self.defaults_write_form(fl_units=new_units)
  4576. # save the defaults to file, some may assume that the conversion is enough and it's not
  4577. self.on_save_button()
  4578. self.should_we_save = True
  4579. # change this only if the workspace is active
  4580. if self.defaults['global_workspace'] is True:
  4581. self.plotcanvas.draw_workspace()
  4582. # adjust the grid values on the main toolbar
  4583. dec = 6 if new_units == 'IN'else 4
  4584. val_x = float(self.ui.grid_gap_x_entry.get_value()) * factor
  4585. self.ui.grid_gap_x_entry.set_value(val_x, decimals=dec)
  4586. if not self.ui.grid_gap_link_cb.isChecked():
  4587. val_y = float(self.ui.grid_gap_y_entry.get_value()) * factor
  4588. self.ui.grid_gap_y_entry.set_value(val_y, decimals=dec)
  4589. for obj in self.collection.get_list():
  4590. obj.convert_units(new_units)
  4591. # make that the properties stored in the object are also updated
  4592. self.object_changed.emit(obj)
  4593. obj.build_ui()
  4594. current = self.collection.get_active()
  4595. if current is not None:
  4596. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  4597. if not isinstance(current, FlatCAMGeometry):
  4598. current.to_form()
  4599. self.plot_all()
  4600. self.inform.emit('[success] %s: %s' %
  4601. (_("Converted units to"), new_units))
  4602. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  4603. self.set_screen_units(new_units)
  4604. else:
  4605. # Undo toggling
  4606. self.toggle_units_ignore = True
  4607. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  4608. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  4609. else:
  4610. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  4611. self.toggle_units_ignore = False
  4612. self.inform.emit('[WARNING_NOTCL]%s' %
  4613. _(" Units conversion cancelled."))
  4614. self.options_read_form()
  4615. self.defaults_read_form()
  4616. def on_toggle_units_click(self):
  4617. try:
  4618. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4619. except (TypeError, AttributeError):
  4620. pass
  4621. if self.defaults["units"] == 'MM':
  4622. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4623. else:
  4624. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4625. self.on_toggle_units(no_pref=True)
  4626. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4627. lambda: self.on_toggle_units(no_pref=False))
  4628. def on_fullscreen(self):
  4629. self.report_usage("on_fullscreen()")
  4630. if self.toggle_fscreen is False:
  4631. if sys.platform == 'win32':
  4632. self.ui.showFullScreen()
  4633. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  4634. tb.setVisible(False)
  4635. self.ui.splitter_left.setVisible(False)
  4636. self.toggle_fscreen = True
  4637. else:
  4638. if sys.platform == 'win32':
  4639. self.ui.showNormal()
  4640. self.restore_toolbar_view()
  4641. self.ui.splitter_left.setVisible(True)
  4642. self.toggle_fscreen = False
  4643. def on_toggle_plotarea(self):
  4644. self.report_usage("on_toggle_plotarea()")
  4645. try:
  4646. name = self.ui.plot_tab_area.widget(0).objectName()
  4647. except AttributeError:
  4648. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4649. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4650. self.ui.plot_tab_area.protectTab(0)
  4651. return
  4652. if name != 'plotarea':
  4653. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  4654. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  4655. self.ui.plot_tab_area.protectTab(0)
  4656. else:
  4657. self.ui.plot_tab_area.closeTab(0)
  4658. def on_toggle_notebook(self):
  4659. if self.ui.splitter.sizes()[0] == 0:
  4660. self.ui.splitter.setSizes([1, 1])
  4661. else:
  4662. self.ui.splitter.setSizes([0, 1])
  4663. def on_toggle_axis(self):
  4664. self.report_usage("on_toggle_axis()")
  4665. if self.toggle_axis is False:
  4666. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4667. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  4668. self.plotcanvas.redraw()
  4669. self.toggle_axis = True
  4670. else:
  4671. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4672. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  4673. self.plotcanvas.redraw()
  4674. self.toggle_axis = False
  4675. def on_toggle_grid(self):
  4676. self.report_usage("on_toggle_grid()")
  4677. self.ui.grid_snap_btn.trigger()
  4678. def on_options_combo_change(self, sel):
  4679. """
  4680. Called when the combo box to choose between application defaults and
  4681. project option changes value. The corresponding variables are
  4682. copied to the UI.
  4683. :param sel: The option index that was chosen.
  4684. :return: None
  4685. """
  4686. # combo_sel = self.ui.notebook.combo_options.get_active()
  4687. App.log.debug("Options --> %s" % sel)
  4688. # form = [self.defaults_form, self.options_form][sel]
  4689. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  4690. if sel == 0:
  4691. self.gen_form = self.ui.general_defaults_form
  4692. self.ger_form = self.ui.gerber_defaults_form
  4693. self.exc_form = self.ui.excellon_defaults_form
  4694. self.geo_form = self.ui.geometry_defaults_form
  4695. self.cnc_form = self.ui.cncjob_defaults_form
  4696. self.tools_form = self.ui.tools_defaults_form
  4697. self.fa_form = self.ui.util_defaults_form
  4698. elif sel == 1:
  4699. self.gen_form = self.ui.general_options_form
  4700. self.ger_form = self.ui.gerber_options_form
  4701. self.exc_form = self.ui.excellon_options_form
  4702. self.geo_form = self.ui.geometry_options_form
  4703. self.cnc_form = self.ui.cncjob_options_form
  4704. self.tools_form = self.ui.tools_options_form
  4705. self.fa_form = self.ui.util_options_form
  4706. else:
  4707. return
  4708. try:
  4709. self.ui.general_scroll_area.takeWidget()
  4710. except:
  4711. self.log.debug("Nothing to remove")
  4712. self.ui.general_scroll_area.setWidget(self.gen_form)
  4713. self.gen_form.show()
  4714. try:
  4715. self.ui.gerber_scroll_area.takeWidget()
  4716. except:
  4717. self.log.debug("Nothing to remove")
  4718. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  4719. self.ger_form.show()
  4720. try:
  4721. self.ui.excellon_scroll_area.takeWidget()
  4722. except:
  4723. self.log.debug("Nothing to remove")
  4724. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  4725. self.exc_form.show()
  4726. try:
  4727. self.ui.geometry_scroll_area.takeWidget()
  4728. except:
  4729. self.log.debug("Nothing to remove")
  4730. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  4731. self.geo_form.show()
  4732. try:
  4733. self.ui.cncjob_scroll_area.takeWidget()
  4734. except:
  4735. self.log.debug("Nothing to remove")
  4736. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  4737. self.cnc_form.show()
  4738. try:
  4739. self.ui.tools_scroll_area.takeWidget()
  4740. except:
  4741. self.log.debug("Nothing to remove")
  4742. self.ui.tools_scroll_area.setWidget(self.tools_form)
  4743. self.tools_form.show()
  4744. try:
  4745. self.ui.fa_scroll_area.takeWidget()
  4746. except:
  4747. self.log.debug("Nothing to remove")
  4748. self.ui.fa_scroll_area.setWidget(self.fa_form)
  4749. self.fa_form.show()
  4750. self.log.debug("Finished GUI form initialization.")
  4751. # self.options2form()
  4752. def on_excellon_defaults_button(self):
  4753. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  4754. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  4755. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  4756. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  4757. self.defaults_form_fields["excellon_zeros"].set_value('L')
  4758. self.defaults_form_fields["excellon_units"].set_value('INCH')
  4759. log.debug("Excellon app defaults loaded ...")
  4760. def on_excellon_options_button(self):
  4761. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  4762. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  4763. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  4764. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  4765. self.options_form_fields["excellon_zeros"].set_value('L')
  4766. self.options_form_fields["excellon_units"].set_value('INCH')
  4767. log.debug("Excellon options defaults loaded ...")
  4768. def on_update_exc_export(self, state):
  4769. """
  4770. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  4771. if the update_excellon_cb checkbox is checked
  4772. :param state: state of the checkbox whose signals is tied to his slot
  4773. :return:
  4774. """
  4775. if state:
  4776. # first try to disconnect
  4777. try:
  4778. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.\
  4779. disconnect(self.on_excellon_format_changed)
  4780. except TypeError:
  4781. pass
  4782. try:
  4783. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.\
  4784. disconnect(self.on_excellon_format_changed)
  4785. except TypeError:
  4786. pass
  4787. try:
  4788. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.\
  4789. disconnect(self.on_excellon_format_changed)
  4790. except TypeError:
  4791. pass
  4792. try:
  4793. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.\
  4794. disconnect(self.on_excellon_format_changed)
  4795. except TypeError:
  4796. pass
  4797. try:
  4798. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  4799. disconnect(self.on_excellon_zeros_changed)
  4800. except TypeError:
  4801. pass
  4802. try:
  4803. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  4804. disconnect(self.on_excellon_zeros_changed)
  4805. except TypeError:
  4806. pass
  4807. # the connect them
  4808. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged.connect(
  4809. self.on_excellon_format_changed)
  4810. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged.connect(
  4811. self.on_excellon_format_changed)
  4812. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged.connect(
  4813. self.on_excellon_format_changed)
  4814. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged.connect(
  4815. self.on_excellon_format_changed)
  4816. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  4817. self.on_excellon_zeros_changed)
  4818. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  4819. self.on_excellon_units_changed)
  4820. else:
  4821. # disconnect the signals
  4822. try:
  4823. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.textChanged. \
  4824. disconnect(self.on_excellon_format_changed)
  4825. except TypeError:
  4826. pass
  4827. try:
  4828. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.textChanged. \
  4829. disconnect(self.on_excellon_format_changed)
  4830. except TypeError:
  4831. pass
  4832. try:
  4833. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.textChanged. \
  4834. disconnect(self.on_excellon_format_changed)
  4835. except TypeError:
  4836. pass
  4837. try:
  4838. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.textChanged. \
  4839. disconnect(self.on_excellon_format_changed)
  4840. except TypeError:
  4841. pass
  4842. try:
  4843. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  4844. disconnect(self.on_excellon_zeros_changed)
  4845. except TypeError:
  4846. pass
  4847. try:
  4848. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  4849. disconnect(self.on_excellon_zeros_changed)
  4850. except TypeError:
  4851. pass
  4852. def on_excellon_format_changed(self):
  4853. """
  4854. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  4855. :return: None
  4856. """
  4857. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  4858. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4859. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  4860. )
  4861. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4862. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  4863. )
  4864. else:
  4865. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  4866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  4867. )
  4868. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  4869. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  4870. )
  4871. def on_excellon_zeros_changed(self):
  4872. """
  4873. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  4874. :return: None
  4875. """
  4876. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  4877. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  4878. )
  4879. def on_excellon_units_changed(self):
  4880. """
  4881. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  4882. :return: None
  4883. """
  4884. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  4885. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  4886. )
  4887. self.on_excellon_format_changed()
  4888. # Setting plot colors handlers
  4889. def on_pf_color_entry(self):
  4890. self.defaults['global_plot_fill'] = \
  4891. self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  4892. self.defaults['global_plot_fill'][7:9]
  4893. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4894. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  4895. def on_pf_color_button(self):
  4896. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  4897. c_dialog = QtWidgets.QColorDialog()
  4898. plot_fill_color = c_dialog.getColor(initial=current_color)
  4899. if plot_fill_color.isValid() is False:
  4900. return
  4901. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  4902. "background-color:%s" % str(plot_fill_color.name()))
  4903. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  4904. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  4905. self.defaults['global_plot_fill'] = new_val
  4906. def on_pf_color_spinner(self):
  4907. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  4908. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  4909. self.defaults['global_plot_fill'] = \
  4910. self.defaults['global_plot_fill'][:7] + \
  4911. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4912. self.defaults['global_plot_line'] = \
  4913. self.defaults['global_plot_line'][:7] + \
  4914. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4915. def on_pf_color_slider(self):
  4916. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  4917. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  4918. def on_pl_color_entry(self):
  4919. self.defaults['global_plot_line'] = \
  4920. self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  4921. self.defaults['global_plot_line'][7:9]
  4922. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4923. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  4924. def on_pl_color_button(self):
  4925. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  4926. # print(current_color)
  4927. c_dialog = QtWidgets.QColorDialog()
  4928. plot_line_color = c_dialog.getColor(initial=current_color)
  4929. if plot_line_color.isValid() is False:
  4930. return
  4931. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  4932. "background-color:%s" % str(plot_line_color.name()))
  4933. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  4934. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  4935. self.defaults['global_plot_line'] = new_val_line
  4936. # Setting selection colors (left - right) handlers
  4937. def on_sf_color_entry(self):
  4938. self.defaults['global_sel_fill'] = \
  4939. self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  4940. self.defaults['global_sel_fill'][7:9]
  4941. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4942. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  4943. def on_sf_color_button(self):
  4944. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  4945. c_dialog = QtWidgets.QColorDialog()
  4946. plot_fill_color = c_dialog.getColor(initial=current_color)
  4947. if plot_fill_color.isValid() is False:
  4948. return
  4949. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  4950. "background-color:%s" % str(plot_fill_color.name()))
  4951. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  4952. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  4953. self.defaults['global_sel_fill'] = new_val
  4954. def on_sf_color_spinner(self):
  4955. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  4956. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  4957. self.defaults['global_sel_fill'] = \
  4958. self.defaults['global_sel_fill'][:7] + \
  4959. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4960. self.defaults['global_sel_line'] = \
  4961. self.defaults['global_sel_line'][:7] + \
  4962. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  4963. def on_sf_color_slider(self):
  4964. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  4965. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  4966. def on_sl_color_entry(self):
  4967. self.defaults['global_sel_line'] = \
  4968. self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  4969. self.defaults['global_sel_line'][7:9]
  4970. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4971. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  4972. def on_sl_color_button(self):
  4973. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  4974. c_dialog = QtWidgets.QColorDialog()
  4975. plot_line_color = c_dialog.getColor(initial=current_color)
  4976. if plot_line_color.isValid() is False:
  4977. return
  4978. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  4979. "background-color:%s" % str(plot_line_color.name()))
  4980. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  4981. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  4982. self.defaults['global_sel_line'] = new_val_line
  4983. # Setting selection colors (right - left) handlers
  4984. def on_alt_sf_color_entry(self):
  4985. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  4986. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  4987. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4988. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  4989. def on_alt_sf_color_button(self):
  4990. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  4991. c_dialog = QtWidgets.QColorDialog()
  4992. plot_fill_color = c_dialog.getColor(initial=current_color)
  4993. if plot_fill_color.isValid() is False:
  4994. return
  4995. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  4996. "background-color:%s" % str(plot_fill_color.name()))
  4997. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  4998. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  4999. self.defaults['global_alt_sel_fill'] = new_val
  5000. def on_alt_sf_color_spinner(self):
  5001. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  5002. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  5003. self.defaults['global_alt_sel_fill'] = \
  5004. self.defaults['global_alt_sel_fill'][:7] + \
  5005. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5006. self.defaults['global_alt_sel_line'] = \
  5007. self.defaults['global_alt_sel_line'][:7] + \
  5008. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  5009. def on_alt_sf_color_slider(self):
  5010. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  5011. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  5012. def on_alt_sl_color_entry(self):
  5013. self.defaults['global_alt_sel_line'] = \
  5014. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.get_value()[:7] + \
  5015. self.defaults['global_alt_sel_line'][7:9]
  5016. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5017. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  5018. def on_alt_sl_color_button(self):
  5019. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  5020. c_dialog = QtWidgets.QColorDialog()
  5021. plot_line_color = c_dialog.getColor(initial=current_color)
  5022. if plot_line_color.isValid() is False:
  5023. return
  5024. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5025. "background-color:%s" % str(plot_line_color.name()))
  5026. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  5027. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  5028. self.defaults['global_alt_sel_line'] = new_val_line
  5029. # Setting Editor colors
  5030. def on_draw_color_entry(self):
  5031. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5032. .draw_color_entry.get_value()
  5033. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5034. "background-color:%s" % str(self.defaults['global_draw_color']))
  5035. def on_draw_color_button(self):
  5036. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  5037. c_dialog = QtWidgets.QColorDialog()
  5038. draw_color = c_dialog.getColor(initial=current_color)
  5039. if draw_color.isValid() is False:
  5040. return
  5041. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5042. "background-color:%s" % str(draw_color.name()))
  5043. new_val = str(draw_color.name())
  5044. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  5045. self.defaults['global_draw_color'] = new_val
  5046. def on_sel_draw_color_entry(self):
  5047. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  5048. .sel_draw_color_entry.get_value()
  5049. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5050. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  5051. def on_sel_draw_color_button(self):
  5052. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  5053. c_dialog = QtWidgets.QColorDialog()
  5054. sel_draw_color = c_dialog.getColor(initial=current_color)
  5055. if sel_draw_color.isValid() is False:
  5056. return
  5057. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5058. "background-color:%s" % str(sel_draw_color.name()))
  5059. new_val_sel = str(sel_draw_color.name())
  5060. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  5061. self.defaults['global_sel_draw_color'] = new_val_sel
  5062. def on_proj_color_entry(self):
  5063. self.defaults['global_proj_item_color'] = self.ui.general_defaults_form.general_gui_group \
  5064. .proj_color_entry.get_value()
  5065. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5066. "background-color:%s" % str(self.defaults['global_proj_item_color']))
  5067. def on_proj_color_button(self):
  5068. current_color = QtGui.QColor(self.defaults['global_proj_item_color'])
  5069. c_dialog = QtWidgets.QColorDialog()
  5070. proj_color = c_dialog.getColor(initial=current_color)
  5071. if proj_color.isValid() is False:
  5072. return
  5073. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5074. "background-color:%s" % str(proj_color.name()))
  5075. new_val_sel = str(proj_color.name())
  5076. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(new_val_sel)
  5077. self.defaults['global_proj_item_color'] = new_val_sel
  5078. def on_proj_color_dis_entry(self):
  5079. self.defaults['global_proj_item_dis_color'] = self.ui.general_defaults_form.general_gui_group \
  5080. .proj_color_dis_entry.get_value()
  5081. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5082. "background-color:%s" % str(self.defaults['global_proj_item_dis_color']))
  5083. def on_proj_color_dis_button(self):
  5084. current_color = QtGui.QColor(self.defaults['global_proj_item_dis_color'])
  5085. c_dialog = QtWidgets.QColorDialog()
  5086. proj_color = c_dialog.getColor(initial=current_color)
  5087. if proj_color.isValid() is False:
  5088. return
  5089. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5090. "background-color:%s" % str(proj_color.name()))
  5091. new_val_sel = str(proj_color.name())
  5092. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(new_val_sel)
  5093. self.defaults['global_proj_item_dis_color'] = new_val_sel
  5094. def on_annotation_fontcolor_entry(self):
  5095. self.defaults['cncjob_annotation_fontcolor'] = \
  5096. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.get_value()
  5097. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5098. "background-color:%s" % str(self.defaults['cncjob_annotation_fontcolor']))
  5099. def on_annotation_fontcolor_button(self):
  5100. current_color = QtGui.QColor(self.defaults['cncjob_annotation_fontcolor'])
  5101. c_dialog = QtWidgets.QColorDialog()
  5102. annotation_color = c_dialog.getColor(initial=current_color)
  5103. if annotation_color.isValid() is False:
  5104. return
  5105. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5106. "background-color:%s" % str(annotation_color.name()))
  5107. new_val_sel = str(annotation_color.name())
  5108. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(new_val_sel)
  5109. self.defaults['cncjob_annotation_fontcolor'] = new_val_sel
  5110. def on_film_color_entry(self):
  5111. self.defaults['tools_film_color'] = \
  5112. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5113. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5114. "background-color:%s" % str(self.defaults['tools_film_color']))
  5115. def on_film_color_button(self):
  5116. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5117. c_dialog = QtWidgets.QColorDialog()
  5118. film_color = c_dialog.getColor(initial=current_color)
  5119. if film_color.isValid() is False:
  5120. return
  5121. # if new color is different then mark that the Preferences are changed
  5122. if film_color != current_color:
  5123. self.on_preferences_edited()
  5124. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5125. "background-color:%s" % str(film_color.name()))
  5126. new_val_sel = str(film_color.name())
  5127. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5128. self.defaults['tools_film_color'] = new_val_sel
  5129. def on_splash_changed(self, state):
  5130. settings = QSettings("Open Source", "FlatCAM")
  5131. settings.setValue('splash_screen', 1) if state else settings.setValue('splash_screen', 0)
  5132. # This will write the setting to the platform specific storage.
  5133. del settings
  5134. def on_notebook_tab_rmb_click(self, checked):
  5135. self.ui.notebook.set_detachable(val=checked)
  5136. self.defaults["global_tabs_detachable"] = checked
  5137. self.ui.plot_tab_area.set_detachable(val=checked)
  5138. self.defaults["global_tabs_detachable"] = checked
  5139. def on_deselect_all(self):
  5140. self.collection.set_all_inactive()
  5141. self.delete_selection_shape()
  5142. def on_workspace_modified(self):
  5143. self.save_defaults(silent=True)
  5144. self.plotcanvas.draw_workspace()
  5145. def on_workspace(self):
  5146. self.report_usage("on_workspace()")
  5147. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5148. self.plotcanvas.restore_workspace()
  5149. else:
  5150. self.plotcanvas.delete_workspace()
  5151. self.save_defaults(silent=True)
  5152. def on_workspace_menu(self):
  5153. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  5154. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  5155. else:
  5156. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  5157. self.on_workspace()
  5158. def on_layout(self, index=None, lay=None):
  5159. self.report_usage("on_layout()")
  5160. if lay:
  5161. current_layout = lay
  5162. else:
  5163. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value()
  5164. settings = QSettings("Open Source", "FlatCAM")
  5165. settings.setValue('layout', current_layout)
  5166. # This will write the setting to the platform specific storage.
  5167. del settings
  5168. # first remove the toolbars:
  5169. try:
  5170. self.ui.removeToolBar(self.ui.toolbarfile)
  5171. self.ui.removeToolBar(self.ui.toolbargeo)
  5172. self.ui.removeToolBar(self.ui.toolbarview)
  5173. self.ui.removeToolBar(self.ui.toolbarshell)
  5174. self.ui.removeToolBar(self.ui.toolbartools)
  5175. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5176. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5177. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5178. self.ui.removeToolBar(self.ui.snap_toolbar)
  5179. self.ui.removeToolBar(self.ui.toolbarshell)
  5180. except Exception as e:
  5181. pass
  5182. if current_layout == 'standard':
  5183. # ## TOOLBAR INSTALLATION # ##
  5184. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5185. self.ui.toolbarfile.setObjectName('File_TB')
  5186. self.ui.addToolBar(self.ui.toolbarfile)
  5187. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5188. self.ui.toolbargeo.setObjectName('Edit_TB')
  5189. self.ui.addToolBar(self.ui.toolbargeo)
  5190. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5191. self.ui.toolbarview.setObjectName('View_TB')
  5192. self.ui.addToolBar(self.ui.toolbarview)
  5193. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5194. self.ui.toolbarshell.setObjectName('Shell_TB')
  5195. self.ui.addToolBar(self.ui.toolbarshell)
  5196. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5197. self.ui.toolbartools.setObjectName('Tools_TB')
  5198. self.ui.addToolBar(self.ui.toolbartools)
  5199. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5200. # self.ui.exc_edit_toolbar.setVisible(False)
  5201. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5202. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5203. self.ui.addToolBarBreak()
  5204. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5205. # self.ui.geo_edit_toolbar.setVisible(False)
  5206. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5207. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5208. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5209. # self.ui.grb_edit_toolbar.setVisible(False)
  5210. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5211. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5212. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5213. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5214. # self.ui.snap_toolbar.setMaximumHeight(30)
  5215. self.ui.addToolBar(self.ui.snap_toolbar)
  5216. self.ui.corner_snap_btn.setVisible(False)
  5217. self.ui.snap_magnet.setVisible(False)
  5218. elif current_layout == 'compact':
  5219. # ## TOOLBAR INSTALLATION # ##
  5220. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5221. self.ui.toolbarfile.setObjectName('File_TB')
  5222. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5223. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5224. self.ui.toolbargeo.setObjectName('Edit_TB')
  5225. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5226. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5227. self.ui.toolbarshell.setObjectName('Shell_TB')
  5228. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5229. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5230. self.ui.toolbartools.setObjectName('Tools_TB')
  5231. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5232. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5233. # self.ui.geo_edit_toolbar.setVisible(False)
  5234. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5235. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5236. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5237. self.ui.toolbarview.setObjectName('View_TB')
  5238. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5239. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5240. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5241. # self.ui.grb_edit_toolbar.setVisible(False)
  5242. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5243. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5244. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5245. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5246. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5247. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5248. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5249. self.ui.snap_toolbar.setMaximumHeight(30)
  5250. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5251. self.ui.corner_snap_btn.setVisible(True)
  5252. self.ui.snap_magnet.setVisible(True)
  5253. # add all the actions to the toolbars
  5254. self.ui.populate_toolbars()
  5255. # reconnect all the signals to the toolbar actions
  5256. self.connect_toolbar_signals()
  5257. self.ui.grid_snap_btn.setChecked(True)
  5258. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5259. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5260. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5261. self.ui.grid_gap_link_cb.setChecked(True)
  5262. def on_cnc_custom_parameters(self, signal_text):
  5263. if signal_text == 'Parameters':
  5264. return
  5265. else:
  5266. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text.insertPlainText('%%%s%%' % signal_text)
  5267. def on_save_button(self):
  5268. log.debug("App.on_save_button() --> Saving preferences to file.")
  5269. self.preferences_changed_flag = False
  5270. self.save_defaults(silent=False)
  5271. # load the defaults so they are updated into the app
  5272. self.load_defaults(filename='current_defaults')
  5273. # Re-fresh project options
  5274. self.on_options_app2project()
  5275. settings = QSettings("Open Source", "FlatCAM")
  5276. # save the notebook font size
  5277. fsize = self.ui.general_defaults_form.general_gui_set_group.notebook_font_size_spinner.get_value()
  5278. settings.setValue('notebook_font_size', fsize)
  5279. # save the axis font size
  5280. g_fsize = self.ui.general_defaults_form.general_gui_set_group.axis_font_size_spinner.get_value()
  5281. settings.setValue('axis_font_size', g_fsize)
  5282. # save the textbox font size
  5283. tb_fsize = self.ui.general_defaults_form.general_gui_set_group.textbox_font_size_spinner.get_value()
  5284. settings.setValue('textbox_font_size', tb_fsize)
  5285. # This will write the setting to the platform specific storage.
  5286. del settings
  5287. def handlePrint(self):
  5288. self.report_usage("handlePrint()")
  5289. dialog = QtPrintSupport.QPrintDialog()
  5290. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  5291. self.ui.code_editor.document().print_(dialog.printer())
  5292. def handlePreview(self):
  5293. self.report_usage("handlePreview()")
  5294. dialog = QtPrintSupport.QPrintPreviewDialog()
  5295. dialog.paintRequested.connect(self.ui.code_editor.print_)
  5296. dialog.exec_()
  5297. def handleTextChanged(self):
  5298. # enable = not self.ui.code_editor.document().isEmpty()
  5299. # self.ui.buttonPrint.setEnabled(enable)
  5300. # self.ui.buttonPreview.setEnabled(enable)
  5301. pass
  5302. def handleOpen(self, filt=None):
  5303. self.report_usage("handleOpen()")
  5304. if filt:
  5305. _filter_ = filt
  5306. else:
  5307. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5308. "All Files (*.*)"
  5309. path, _f = QtWidgets.QFileDialog.getOpenFileName(
  5310. caption=_('Open file'), directory=self.get_last_folder(), filter=_filter_)
  5311. if path:
  5312. file = QtCore.QFile(path)
  5313. if file.open(QtCore.QIODevice.ReadOnly):
  5314. stream = QtCore.QTextStream(file)
  5315. self.gcode_edited = stream.readAll()
  5316. self.ui.code_editor.setPlainText(self.gcode_edited)
  5317. file.close()
  5318. def handleSaveGCode(self, name=None, filt=None):
  5319. self.report_usage("handleSaveGCode()")
  5320. if filt:
  5321. _filter_ = filt
  5322. else:
  5323. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  5324. "All Files (*.*)"
  5325. if name:
  5326. obj_name = name
  5327. else:
  5328. try:
  5329. obj_name = self.collection.get_active().options['name']
  5330. except AttributeError:
  5331. obj_name = 'file'
  5332. if filt is None:
  5333. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  5334. try:
  5335. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  5336. caption=_("Export G-Code ..."),
  5337. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  5338. filter=_filter_
  5339. )[0])
  5340. except TypeError:
  5341. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption=_("Export G-Code ..."), filter=_filter_)[0])
  5342. if filename == "":
  5343. self.inform.emit('[WARNING_NOTCL] %s' %
  5344. _("Export Code cancelled."))
  5345. return
  5346. else:
  5347. try:
  5348. my_gcode = self.ui.code_editor.toPlainText()
  5349. with open(filename, 'w') as f:
  5350. for line in my_gcode:
  5351. f.write(line)
  5352. except FileNotFoundError:
  5353. self.inform.emit('[WARNING] %s' %
  5354. _("No such file or directory"))
  5355. return
  5356. except PermissionError:
  5357. self.inform.emit('[WARNING] %s' %
  5358. _("Permission denied, saving not possible.\n"
  5359. "Most likely another app is holding the file open and not accessible."))
  5360. return
  5361. # Just for adding it to the recent files list.
  5362. if self.defaults["global_open_style"] is False:
  5363. self.file_opened.emit("cncjob", filename)
  5364. self.file_saved.emit("cncjob", filename)
  5365. self.inform.emit('%s: %s' % (_("Saved to"), str(filename)))
  5366. def handleFindGCode(self):
  5367. self.report_usage("handleFindGCode()")
  5368. flags = QtGui.QTextDocument.FindCaseSensitively
  5369. text_to_be_found = self.ui.entryFind.get_value()
  5370. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  5371. if r is False:
  5372. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5373. def handleReplaceGCode(self):
  5374. self.report_usage("handleReplaceGCode()")
  5375. old = self.ui.entryFind.get_value()
  5376. new = self.ui.entryReplace.get_value()
  5377. if self.ui.sel_all_cb.isChecked():
  5378. while True:
  5379. cursor = self.ui.code_editor.textCursor()
  5380. cursor.beginEditBlock()
  5381. flags = QtGui.QTextDocument.FindCaseSensitively
  5382. # self.ui.editor is the QPlainTextEdit
  5383. r = self.ui.code_editor.find(str(old), flags)
  5384. if r:
  5385. qc = self.ui.code_editor.textCursor()
  5386. if qc.hasSelection():
  5387. qc.insertText(new)
  5388. else:
  5389. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  5390. break
  5391. # Mark end of undo block
  5392. cursor.endEditBlock()
  5393. else:
  5394. cursor = self.ui.code_editor.textCursor()
  5395. cursor.beginEditBlock()
  5396. qc = self.ui.code_editor.textCursor()
  5397. if qc.hasSelection():
  5398. qc.insertText(new)
  5399. # Mark end of undo block
  5400. cursor.endEditBlock()
  5401. def handleRunCode(self):
  5402. # trying to run a Tcl command without having the Shell open will create some warnings because the Tcl Shell
  5403. # tries to print on a hidden widget, therefore show the dock if hidden
  5404. if self.ui.shell_dock.isHidden():
  5405. self.ui.shell_dock.show()
  5406. self.script_code = deepcopy(self.ui.code_editor.toPlainText())
  5407. # self.shell._sysShell.exec_command(script_code)
  5408. old_line = ''
  5409. for tcl_command_line in self.script_code.splitlines():
  5410. # do not process lines starting with '#' = comment and empty lines
  5411. if not tcl_command_line.startswith('#') and tcl_command_line != '':
  5412. # id FlatCAM is run in Windows then replace all the slashes with
  5413. # the UNIX style slash that TCL understands
  5414. if sys.platform == 'win32':
  5415. if "open" in tcl_command_line:
  5416. tcl_command_line = tcl_command_line.replace('\\', '/')
  5417. if old_line != '':
  5418. new_command = old_line + tcl_command_line + '\n'
  5419. else:
  5420. new_command = tcl_command_line
  5421. # execute the actual Tcl command
  5422. try:
  5423. self.shell.open_proccessing() # Disables input box.
  5424. result = self.tcl.eval(str(new_command))
  5425. if result != 'None':
  5426. self.shell.append_output(result + '\n')
  5427. old_line = ''
  5428. except tk.TclError:
  5429. old_line = old_line + tcl_command_line + '\n'
  5430. except Exception as e:
  5431. log.debug("App.handleRunCode() --> %s" % str(e))
  5432. if old_line != '':
  5433. # it means that the script finished with an error
  5434. result = self.tcl.eval("set errorInfo")
  5435. self.log.error("Exec command Exception: %s" % (result + '\n'))
  5436. self.shell.append_error('ERROR: ' + result + '\n')
  5437. self.shell.close_proccessing()
  5438. def on_tool_add_keypress(self):
  5439. # ## Current application units in Upper Case
  5440. self.units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  5441. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5442. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5443. if notebook_widget_name == 'selected_tab':
  5444. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5445. # Tool add works for Geometry only if Advanced is True in Preferences
  5446. if self.defaults["global_app_level"] == 'a':
  5447. tool_add_popup = FCInputDialog(title="New Tool ...",
  5448. text='Enter a Tool Diameter:',
  5449. min=0.0000, max=99.9999, decimals=4)
  5450. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5451. val, ok = tool_add_popup.get_value()
  5452. if ok:
  5453. if float(val) == 0:
  5454. self.inform.emit('[WARNING_NOTCL] %s' %
  5455. _("Please enter a tool diameter with non-zero value, in Float format."))
  5456. return
  5457. self.collection.get_active().on_tool_add(dia=float(val))
  5458. else:
  5459. self.inform.emit('[WARNING_NOTCL] %s...' %
  5460. _("Adding Tool cancelled"))
  5461. else:
  5462. msgbox = QtWidgets.QMessageBox()
  5463. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5464. "Go to Preferences -> General - Show Advanced Options."))
  5465. msgbox.setWindowTitle("Tool adding ...")
  5466. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  5467. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5468. msgbox.setDefaultButton(bt_ok)
  5469. msgbox.exec_()
  5470. # work only if the notebook tab on focus is the Tools_Tab
  5471. if notebook_widget_name == 'tool_tab':
  5472. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5473. tool_add_popup = FCInputDialog(title="New Tool ...",
  5474. text='Enter a Tool Diameter:',
  5475. min=0.0000, max=99.9999, decimals=4)
  5476. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  5477. val, ok = tool_add_popup.get_value()
  5478. # and only if the tool is NCC Tool
  5479. if tool_widget == self.ncclear_tool.toolName:
  5480. if ok:
  5481. if float(val) == 0:
  5482. self.inform.emit('[WARNING_NOTCL] %s' %
  5483. _("Please enter a tool diameter with non-zero value, in Float format."))
  5484. return
  5485. self.ncclear_tool.on_tool_add(dia=float(val))
  5486. else:
  5487. self.inform.emit('[WARNING_NOTCL] %s...' %
  5488. _("Adding Tool cancelled"))
  5489. # and only if the tool is Paint Area Tool
  5490. elif tool_widget == self.paint_tool.toolName:
  5491. if ok:
  5492. if float(val) == 0:
  5493. self.inform.emit('[WARNING_NOTCL] %s' %
  5494. _("Please enter a tool diameter with non-zero value, in Float format."))
  5495. return
  5496. self.paint_tool.on_tool_add(dia=float(val))
  5497. else:
  5498. self.inform.emit('[WARNING_NOTCL] %s...' %
  5499. _("Adding Tool cancelled"))
  5500. # and only if the tool is Solder Paste Dispensing Tool
  5501. elif tool_widget == self.paste_tool.toolName:
  5502. if ok:
  5503. if float(val) == 0:
  5504. self.inform.emit('[WARNING_NOTCL] %s' %
  5505. _("Please enter a tool diameter with non-zero value, in Float format."))
  5506. return
  5507. self.paste_tool.on_tool_add(dia=float(val))
  5508. else:
  5509. self.inform.emit('[WARNING_NOTCL] %s...' %
  5510. _("Adding Tool cancelled"))
  5511. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5512. # See description bellow.
  5513. def on_delete_keypress(self):
  5514. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5515. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5516. if notebook_widget_name == 'selected_tab':
  5517. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5518. self.collection.get_active().on_tool_delete()
  5519. # work only if the notebook tab on focus is the Tools_Tab
  5520. elif notebook_widget_name == 'tool_tab':
  5521. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5522. # and only if the tool is NCC Tool
  5523. if tool_widget == self.ncclear_tool.toolName:
  5524. self.ncclear_tool.on_tool_delete()
  5525. # and only if the tool is Paint Tool
  5526. elif tool_widget == self.paint_tool.toolName:
  5527. self.paint_tool.on_tool_delete()
  5528. # and only if the tool is Solder Paste Dispensing Tool
  5529. elif tool_widget == self.paste_tool.toolName:
  5530. self.paste_tool.on_tool_delete()
  5531. else:
  5532. self.on_delete()
  5533. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5534. # some screens you have to be careful where you hover with your mouse.
  5535. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5536. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5537. # Complicated, I know :)
  5538. def on_delete(self):
  5539. """
  5540. Delete the currently selected FlatCAMObjs.
  5541. :return: None
  5542. """
  5543. self.report_usage("on_delete()")
  5544. response = None
  5545. bt_ok = None
  5546. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5547. # a geometry object before we update it.
  5548. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5549. and self.grb_editor.editor_active is False:
  5550. if self.defaults["global_delete_confirmation"] is True:
  5551. msgbox = QtWidgets.QMessageBox()
  5552. msgbox.setWindowTitle(_("Delete objects"))
  5553. msgbox.setWindowIcon(QtGui.QIcon('share/deleteshape32.png'))
  5554. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5555. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5556. "the selected objects?"))
  5557. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5558. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5559. msgbox.setDefaultButton(bt_ok)
  5560. msgbox.exec_()
  5561. response = msgbox.clickedButton()
  5562. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5563. if self.collection.get_active():
  5564. self.log.debug("App.on_delete()")
  5565. while self.collection.get_active():
  5566. obj_active = self.collection.get_active()
  5567. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5568. if isinstance(obj_active, FlatCAMGerber):
  5569. for el in obj_active.mark_shapes:
  5570. obj_active.mark_shapes[el].clear(update=True)
  5571. obj_active.mark_shapes[el].enabled = False
  5572. # obj_active.mark_shapes[el] = None
  5573. del el
  5574. elif isinstance(obj_active, FlatCAMCNCjob):
  5575. try:
  5576. obj_active.annotation.clear(update=True)
  5577. obj_active.annotation.enabled = False
  5578. except AttributeError:
  5579. pass
  5580. self.delete_first_selected()
  5581. self.inform.emit('%s...' %
  5582. _("Object(s) deleted"))
  5583. # make sure that the selection shape is deleted, too
  5584. self.delete_selection_shape()
  5585. else:
  5586. self.inform.emit(_("Failed. No object(s) selected..."))
  5587. else:
  5588. self.inform.emit(_("Save the work in Editor and try again ..."))
  5589. def delete_first_selected(self):
  5590. # Keep this for later
  5591. try:
  5592. sel_obj = self.collection.get_active()
  5593. name = sel_obj.options["name"]
  5594. except AttributeError:
  5595. self.log.debug("Nothing selected for deletion")
  5596. return
  5597. # Remove from dictionary
  5598. self.collection.delete_active()
  5599. # Clear form
  5600. self.setup_component_editor()
  5601. self.inform.emit('%s: %s' %
  5602. (_("Object deleted"), name))
  5603. def on_set_origin(self):
  5604. """
  5605. Set the origin to the left mouse click position
  5606. :return: None
  5607. """
  5608. # display the message for the user
  5609. # and ask him to click on the desired position
  5610. self.report_usage("on_set_origin()")
  5611. def origin_replot():
  5612. def worker_task():
  5613. with self.proc_container.new('%s...' % _("Plotting")):
  5614. for obj in self.collection.get_list():
  5615. obj.plot()
  5616. self.plotcanvas.fit_view()
  5617. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  5618. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5619. self.inform.emit(_('Click to set the origin ...'))
  5620. self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  5621. # first disconnect it as it may have been used by something else
  5622. try:
  5623. self.replot_signal.disconnect()
  5624. except TypeError:
  5625. pass
  5626. self.replot_signal[list].connect(origin_replot)
  5627. def on_set_zero_click(self, event):
  5628. # this function will be available only for mouse left click
  5629. pos_canvas = self.plotcanvas.translate_coords(event.pos)
  5630. if event.button == 1:
  5631. if self.grid_status() == True:
  5632. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5633. else:
  5634. pos = pos_canvas
  5635. x = 0 - pos[0]
  5636. y = 0 - pos[1]
  5637. def worker_task():
  5638. with self.proc_container.new(_("Setting Origin...")):
  5639. for obj in self.collection.get_list():
  5640. obj.offset((x, y))
  5641. self.object_changed.emit(obj)
  5642. # Update the object bounding box options
  5643. a, b, c, d = obj.bounds()
  5644. obj.options['xmin'] = a
  5645. obj.options['ymin'] = b
  5646. obj.options['xmax'] = c
  5647. obj.options['ymax'] = d
  5648. self.inform.emit('[success]%s...' %
  5649. _('Origin set'))
  5650. self.replot_signal.emit([])
  5651. self.worker_task.emit({'fcn': worker_task, 'params': []})
  5652. self.should_we_save = True
  5653. def on_jump_to(self, custom_location=None, fit_center=True):
  5654. """
  5655. Jump to a location by setting the mouse cursor location
  5656. :return:
  5657. """
  5658. self.report_usage("on_jump_to()")
  5659. if not custom_location:
  5660. dia_box = Dialog_box(title=_("Jump to ..."),
  5661. label=_("Enter the coordinates in format X,Y:"),
  5662. icon=QtGui.QIcon('share/jump_to16.png'))
  5663. if dia_box.ok is True:
  5664. try:
  5665. location = eval(dia_box.location)
  5666. if not isinstance(location, tuple):
  5667. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  5668. return
  5669. except:
  5670. return
  5671. else:
  5672. return
  5673. else:
  5674. location = custom_location
  5675. if fit_center:
  5676. self.plotcanvas.fit_center(loc=location)
  5677. cursor = QtGui.QCursor()
  5678. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  5679. jump_loc = self.plotcanvas.translate_coords_2((location[0], location[1]))
  5680. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  5681. self.inform.emit('[success] %s' %
  5682. _("Done."))
  5683. return location
  5684. def on_copy_object(self):
  5685. self.report_usage("on_copy_object()")
  5686. def initialize(obj_init, app):
  5687. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5688. try:
  5689. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5690. except AttributeError:
  5691. pass
  5692. try:
  5693. obj_init.apertures = deepcopy(obj.apertures)
  5694. except AttributeError:
  5695. pass
  5696. try:
  5697. if obj.tools:
  5698. obj_init.tools = deepcopy(obj.tools)
  5699. except Exception as e:
  5700. log.debug("App.on_copy_object() --> %s" % str(e))
  5701. def initialize_excellon(obj_init, app):
  5702. obj_init.tools = deepcopy(obj.tools)
  5703. # drills are offset, so they need to be deep copied
  5704. obj_init.drills = deepcopy(obj.drills)
  5705. # slots are offset, so they need to be deep copied
  5706. obj_init.slots = deepcopy(obj.slots)
  5707. obj_init.create_geometry()
  5708. for obj in self.collection.get_selected():
  5709. obj_name = obj.options["name"]
  5710. try:
  5711. if isinstance(obj, FlatCAMExcellon):
  5712. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  5713. elif isinstance(obj, FlatCAMGerber):
  5714. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  5715. elif isinstance(obj, FlatCAMGeometry):
  5716. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  5717. except Exception as e:
  5718. return "Operation failed: %s" % str(e)
  5719. def on_copy_object2(self, custom_name):
  5720. def initialize_geometry(obj_init, app):
  5721. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5722. try:
  5723. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  5724. except AttributeError:
  5725. pass
  5726. try:
  5727. obj_init.apertures = deepcopy(obj.apertures)
  5728. except AttributeError:
  5729. pass
  5730. try:
  5731. if obj.tools:
  5732. obj_init.tools = deepcopy(obj.tools)
  5733. except Exception as e:
  5734. log.debug("on_copy_object2() --> %s" % str(e))
  5735. def initialize_gerber(obj_init, app):
  5736. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5737. obj_init.apertures = deepcopy(obj.apertures)
  5738. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  5739. def initialize_excellon(obj_init, app):
  5740. obj_init.tools = deepcopy(obj.tools)
  5741. # drills are offset, so they need to be deep copied
  5742. obj_init.drills = deepcopy(obj.drills)
  5743. # slots are offset, so they need to be deep copied
  5744. obj_init.slots = deepcopy(obj.slots)
  5745. obj_init.create_geometry()
  5746. for obj in self.collection.get_selected():
  5747. obj_name = obj.options["name"]
  5748. try:
  5749. if isinstance(obj, FlatCAMExcellon):
  5750. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  5751. elif isinstance(obj, FlatCAMGerber):
  5752. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  5753. elif isinstance(obj, FlatCAMGeometry):
  5754. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  5755. except Exception as e:
  5756. return "Operation failed: %s" % str(e)
  5757. def on_rename_object(self, text):
  5758. self.report_usage("on_rename_object()")
  5759. named_obj = self.collection.get_active()
  5760. for obj in named_obj:
  5761. if obj is list:
  5762. self.on_rename_object(text)
  5763. else:
  5764. try:
  5765. obj.options['name'] = text
  5766. except Exception as e:
  5767. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  5768. def convert_any2geo(self):
  5769. self.report_usage("convert_any2geo()")
  5770. def initialize(obj_init, app):
  5771. obj_init.solid_geometry = obj.solid_geometry
  5772. try:
  5773. obj_init.follow_geometry = obj.follow_geometry
  5774. except AttributeError:
  5775. pass
  5776. try:
  5777. obj_init.apertures = obj.apertures
  5778. except AttributeError:
  5779. pass
  5780. try:
  5781. if obj.tools:
  5782. obj_init.tools = obj.tools
  5783. except AttributeError:
  5784. pass
  5785. def initialize_excellon(obj_init, app):
  5786. # objs = self.collection.get_selected()
  5787. # FlatCAMGeometry.merge(objs, obj)
  5788. solid_geo = []
  5789. for tool in obj.tools:
  5790. for geo in obj.tools[tool]['solid_geometry']:
  5791. solid_geo.append(geo)
  5792. obj_init.solid_geometry = deepcopy(solid_geo)
  5793. if not self.collection.get_selected():
  5794. log.warning("App.convert_any2geo --> No object selected")
  5795. self.inform.emit('[WARNING_NOTCL] %s' %
  5796. _("No object is selected. Select an object and try again."))
  5797. return
  5798. for obj in self.collection.get_selected():
  5799. obj_name = obj.options["name"]
  5800. try:
  5801. if isinstance(obj, FlatCAMExcellon):
  5802. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  5803. else:
  5804. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  5805. except Exception as e:
  5806. return "Operation failed: %s" % str(e)
  5807. def convert_any2gerber(self):
  5808. self.report_usage("convert_any2gerber()")
  5809. def initialize_geometry(obj_init, app):
  5810. apertures = {}
  5811. apid = 0
  5812. apertures[str(apid)] = {}
  5813. apertures[str(apid)]['geometry'] = []
  5814. for obj_orig in obj.solid_geometry:
  5815. new_elem = dict()
  5816. new_elem['solid'] = obj_orig
  5817. new_elem['follow'] = obj_orig.exterior
  5818. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  5819. apertures[str(apid)]['size'] = 0.0
  5820. apertures[str(apid)]['type'] = 'C'
  5821. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  5822. obj_init.apertures = deepcopy(apertures)
  5823. def initialize_excellon(obj_init, app):
  5824. apertures = {}
  5825. apid = 10
  5826. for tool in obj.tools:
  5827. apertures[str(apid)] = {}
  5828. apertures[str(apid)]['geometry'] = []
  5829. for geo in obj.tools[tool]['solid_geometry']:
  5830. new_el = dict()
  5831. new_el['solid'] = geo
  5832. new_el['follow'] = geo.exterior
  5833. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  5834. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  5835. apertures[str(apid)]['type'] = 'C'
  5836. apid += 1
  5837. # create solid_geometry
  5838. solid_geometry = []
  5839. for apid in apertures:
  5840. for geo_el in apertures[apid]['geometry']:
  5841. solid_geometry.append(geo_el['solid'])
  5842. solid_geometry = MultiPolygon(solid_geometry)
  5843. solid_geometry = solid_geometry.buffer(0.0000001)
  5844. obj_init.solid_geometry = deepcopy(solid_geometry)
  5845. obj_init.apertures = deepcopy(apertures)
  5846. # clear the working objects (perhaps not necessary due of Python GC)
  5847. apertures.clear()
  5848. if not self.collection.get_selected():
  5849. log.warning("App.convert_any2gerber --> No object selected")
  5850. self.inform.emit('[WARNING_NOTCL] %s' %
  5851. _("No object is selected. Select an object and try again."))
  5852. return
  5853. for obj in self.collection.get_selected():
  5854. obj_name = obj.options["name"]
  5855. try:
  5856. if isinstance(obj, FlatCAMExcellon):
  5857. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  5858. elif isinstance(obj, FlatCAMGeometry):
  5859. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  5860. else:
  5861. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  5862. except Exception as e:
  5863. return "Operation failed: %s" % str(e)
  5864. def abort_all_tasks(self):
  5865. if self.abort_flag is False:
  5866. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  5867. self.abort_flag = True
  5868. def app_is_idle(self):
  5869. if self.abort_flag:
  5870. self.inform.emit('[WARNING_NOTCL] %s' %
  5871. _("The current task was gracefully closed on user request..."))
  5872. self.abort_flag = False
  5873. def on_selectall(self):
  5874. self.report_usage("on_selectall()")
  5875. # delete the possible selection box around a possible selected object
  5876. self.delete_selection_shape()
  5877. for name in self.collection.get_names():
  5878. self.collection.set_active(name)
  5879. curr_sel_obj = self.collection.get_by_name(name)
  5880. # create the selection box around the selected object
  5881. if self.defaults['global_selection_shape'] is True:
  5882. self.draw_selection_shape(curr_sel_obj)
  5883. def on_preferences(self):
  5884. # add the tab if it was closed
  5885. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  5886. # delete the absolute and relative position and messages in the infobar
  5887. self.ui.position_label.setText("")
  5888. self.ui.rel_position_label.setText("")
  5889. # Switch plot_area to preferences page
  5890. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  5891. # self.ui.show()
  5892. # this disconnect() is done so the slot will be connected only once
  5893. try:
  5894. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_preferences_closed)
  5895. except (TypeError, AttributeError):
  5896. pass
  5897. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_preferences_closed)
  5898. # detect changes in the preferences
  5899. for idx in range(self.ui.pref_tab_area.count()):
  5900. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5901. try:
  5902. try:
  5903. tb.textEdited.disconnect(self.on_preferences_edited)
  5904. except (TypeError, AttributeError):
  5905. pass
  5906. tb.textEdited.connect(self.on_preferences_edited)
  5907. except AttributeError:
  5908. pass
  5909. try:
  5910. try:
  5911. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5912. except (TypeError, AttributeError):
  5913. pass
  5914. tb.modificationChanged.connect(self.on_preferences_edited)
  5915. except AttributeError:
  5916. pass
  5917. try:
  5918. try:
  5919. tb.toggled.disconnect(self.on_preferences_edited)
  5920. except (TypeError, AttributeError):
  5921. pass
  5922. tb.toggled.connect(self.on_preferences_edited)
  5923. except AttributeError:
  5924. pass
  5925. try:
  5926. try:
  5927. tb.valueChanged.disconnect(self.on_preferences_edited)
  5928. except (TypeError, AttributeError):
  5929. pass
  5930. tb.valueChanged.connect(self.on_preferences_edited)
  5931. except AttributeError:
  5932. pass
  5933. try:
  5934. try:
  5935. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5936. except (TypeError, AttributeError):
  5937. pass
  5938. tb.currentIndexChanged.connect(self.on_preferences_edited)
  5939. except AttributeError:
  5940. pass
  5941. def on_preferences_edited(self):
  5942. self.inform.emit('[WARNING_NOTCL] %s' %
  5943. _("Preferences edited but not saved."))
  5944. self.preferences_changed_flag = True
  5945. def on_preferences_closed(self):
  5946. # disconnect
  5947. for idx in range(self.ui.pref_tab_area.count()):
  5948. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  5949. try:
  5950. tb.textEdited.disconnect(self.on_preferences_edited)
  5951. except (TypeError, AttributeError):
  5952. pass
  5953. try:
  5954. tb.modificationChanged.disconnect(self.on_preferences_edited)
  5955. except (TypeError, AttributeError):
  5956. pass
  5957. try:
  5958. tb.toggled.disconnect(self.on_preferences_edited)
  5959. except (TypeError, AttributeError):
  5960. pass
  5961. try:
  5962. tb.valueChanged.disconnect(self.on_preferences_edited)
  5963. except (TypeError, AttributeError):
  5964. pass
  5965. try:
  5966. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  5967. except (TypeError, AttributeError):
  5968. pass
  5969. if self.preferences_changed_flag is True:
  5970. msgbox = QtWidgets.QMessageBox()
  5971. msgbox.setText(_("One or more values are changed.\n"
  5972. "Do you want to save the Preferences?"))
  5973. msgbox.setWindowTitle(_("Save Preferences"))
  5974. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  5975. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5976. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5977. msgbox.setDefaultButton(bt_yes)
  5978. msgbox.exec_()
  5979. response = msgbox.clickedButton()
  5980. if response == bt_yes:
  5981. self.on_save_button()
  5982. self.inform.emit('[success] %s' %
  5983. _("Preferences saved."))
  5984. else:
  5985. self.preferences_changed_flag = False
  5986. return
  5987. def on_flipy(self):
  5988. self.report_usage("on_flipy()")
  5989. obj_list = self.collection.get_selected()
  5990. xminlist = []
  5991. yminlist = []
  5992. xmaxlist = []
  5993. ymaxlist = []
  5994. if not obj_list:
  5995. self.inform.emit('[WARNING_NOTCL] %s' %
  5996. _("No object selected to Flip on Y axis."))
  5997. else:
  5998. try:
  5999. # first get a bounding box to fit all
  6000. for obj in obj_list:
  6001. xmin, ymin, xmax, ymax = obj.bounds()
  6002. xminlist.append(xmin)
  6003. yminlist.append(ymin)
  6004. xmaxlist.append(xmax)
  6005. ymaxlist.append(ymax)
  6006. # get the minimum x,y and maximum x,y for all objects selected
  6007. xminimal = min(xminlist)
  6008. yminimal = min(yminlist)
  6009. xmaximal = max(xmaxlist)
  6010. ymaximal = max(ymaxlist)
  6011. px = 0.5 * (xminimal + xmaximal)
  6012. py = 0.5 * (yminimal + ymaximal)
  6013. # execute mirroring
  6014. for obj in obj_list:
  6015. obj.mirror('X', [px, py])
  6016. obj.plot()
  6017. self.object_changed.emit(obj)
  6018. self.inform.emit('[success] %s' %
  6019. _("Flip on Y axis done."))
  6020. except Exception as e:
  6021. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6022. (_("Flip action was not executed."), str(e)))
  6023. return
  6024. def on_flipx(self):
  6025. self.report_usage("on_flipx()")
  6026. obj_list = self.collection.get_selected()
  6027. xminlist = []
  6028. yminlist = []
  6029. xmaxlist = []
  6030. ymaxlist = []
  6031. if not obj_list:
  6032. self.inform.emit('[WARNING_NOTCL] %s' %
  6033. _("No object selected to Flip on X axis."))
  6034. else:
  6035. try:
  6036. # first get a bounding box to fit all
  6037. for obj in obj_list:
  6038. xmin, ymin, xmax, ymax = obj.bounds()
  6039. xminlist.append(xmin)
  6040. yminlist.append(ymin)
  6041. xmaxlist.append(xmax)
  6042. ymaxlist.append(ymax)
  6043. # get the minimum x,y and maximum x,y for all objects selected
  6044. xminimal = min(xminlist)
  6045. yminimal = min(yminlist)
  6046. xmaximal = max(xmaxlist)
  6047. ymaximal = max(ymaxlist)
  6048. px = 0.5 * (xminimal + xmaximal)
  6049. py = 0.5 * (yminimal + ymaximal)
  6050. # execute mirroring
  6051. for obj in obj_list:
  6052. obj.mirror('Y', [px, py])
  6053. obj.plot()
  6054. self.object_changed.emit(obj)
  6055. self.inform.emit('[success] %s' %
  6056. _("Flip on X axis done."))
  6057. except Exception as e:
  6058. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6059. (_("Flip action was not executed."), str(e)))
  6060. return
  6061. def on_rotate(self, silent=False, preset=None):
  6062. self.report_usage("on_rotate()")
  6063. obj_list = self.collection.get_selected()
  6064. xminlist = []
  6065. yminlist = []
  6066. xmaxlist = []
  6067. ymaxlist = []
  6068. if not obj_list:
  6069. self.inform.emit('[WARNING_NOTCL] %s' %
  6070. _("No object selected to Rotate."))
  6071. else:
  6072. if silent is False:
  6073. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6074. min=-360, max=360, decimals=4,
  6075. init_val=float(self.defaults['tools_transform_rotate']))
  6076. num, ok = rotatebox.get_value()
  6077. else:
  6078. num = preset
  6079. ok = True
  6080. if ok:
  6081. try:
  6082. # first get a bounding box to fit all
  6083. for obj in obj_list:
  6084. xmin, ymin, xmax, ymax = obj.bounds()
  6085. xminlist.append(xmin)
  6086. yminlist.append(ymin)
  6087. xmaxlist.append(xmax)
  6088. ymaxlist.append(ymax)
  6089. # get the minimum x,y and maximum x,y for all objects selected
  6090. xminimal = min(xminlist)
  6091. yminimal = min(yminlist)
  6092. xmaximal = max(xmaxlist)
  6093. ymaximal = max(ymaxlist)
  6094. px = 0.5 * (xminimal + xmaximal)
  6095. py = 0.5 * (yminimal + ymaximal)
  6096. for sel_obj in obj_list:
  6097. sel_obj.rotate(-float(num), point=(px, py))
  6098. sel_obj.plot()
  6099. self.object_changed.emit(sel_obj)
  6100. self.inform.emit('[success] %s' %
  6101. _("Rotation done."))
  6102. except Exception as e:
  6103. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  6104. (_("Rotation movement was not executed."), str(e)))
  6105. return
  6106. def on_skewx(self):
  6107. self.report_usage("on_skewx()")
  6108. obj_list = self.collection.get_selected()
  6109. xminlist = []
  6110. yminlist = []
  6111. if not obj_list:
  6112. self.inform.emit('[WARNING_NOTCL] %s' %
  6113. _("No object selected to Skew/Shear on X axis."))
  6114. else:
  6115. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6116. min=-360, max=360, decimals=4,
  6117. init_val=float(self.defaults['tools_transform_skew_x']))
  6118. num, ok = skewxbox.get_value()
  6119. if ok:
  6120. # first get a bounding box to fit all
  6121. for obj in obj_list:
  6122. xmin, ymin, xmax, ymax = obj.bounds()
  6123. xminlist.append(xmin)
  6124. yminlist.append(ymin)
  6125. # get the minimum x,y and maximum x,y for all objects selected
  6126. xminimal = min(xminlist)
  6127. yminimal = min(yminlist)
  6128. for obj in obj_list:
  6129. obj.skew(num, 0, point=(xminimal, yminimal))
  6130. obj.plot()
  6131. self.object_changed.emit(obj)
  6132. self.inform.emit('[success] %s' %
  6133. _("Skew on X axis done."))
  6134. def on_skewy(self):
  6135. self.report_usage("on_skewy()")
  6136. obj_list = self.collection.get_selected()
  6137. xminlist = []
  6138. yminlist = []
  6139. if not obj_list:
  6140. self.inform.emit('[WARNING_NOTCL] %s' %
  6141. _("No object selected to Skew/Shear on Y axis."))
  6142. else:
  6143. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6144. min=-360, max=360, decimals=4,
  6145. init_val=float(self.defaults['tools_transform_skew_y']))
  6146. num, ok = skewybox.get_value()
  6147. if ok:
  6148. # first get a bounding box to fit all
  6149. for obj in obj_list:
  6150. xmin, ymin, xmax, ymax = obj.bounds()
  6151. xminlist.append(xmin)
  6152. yminlist.append(ymin)
  6153. # get the minimum x,y and maximum x,y for all objects selected
  6154. xminimal = min(xminlist)
  6155. yminimal = min(yminlist)
  6156. for obj in obj_list:
  6157. obj.skew(0, num, point=(xminimal, yminimal))
  6158. obj.plot()
  6159. self.object_changed.emit(obj)
  6160. self.inform.emit('[success] %s' %
  6161. _("Skew on Y axis done."))
  6162. def on_plots_updated(self):
  6163. """
  6164. Callback used to report when the plots have changed.
  6165. Adjust axes and zooms to fit.
  6166. :return: None
  6167. """
  6168. self.plotcanvas.update() # TODO: Need update canvas?
  6169. self.on_zoom_fit(None)
  6170. self.collection.update_view()
  6171. # self.inform.emit(_("Plots updated ..."))
  6172. # TODO: Rework toolbar 'clear', 'replot' functions
  6173. def on_toolbar_replot(self):
  6174. """
  6175. Callback for toolbar button. Re-plots all objects.
  6176. :return: None
  6177. """
  6178. self.report_usage("on_toolbar_replot")
  6179. self.log.debug("on_toolbar_replot()")
  6180. try:
  6181. self.collection.get_active().read_form()
  6182. except AttributeError:
  6183. self.log.debug("on_toolbar_replot(): AttributeError")
  6184. pass
  6185. self.plot_all()
  6186. def on_row_activated(self, index):
  6187. if index.isValid():
  6188. if index.internalPointer().parent_item != self.collection.root_item:
  6189. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6190. self.collection.on_item_activated(index)
  6191. def grid_status(self):
  6192. if self.ui.grid_snap_btn.isChecked():
  6193. return True
  6194. else:
  6195. return False
  6196. def populate_cmenu_grids(self):
  6197. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6198. self.ui.cmenu_gridmenu.clear()
  6199. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  6200. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), _("Grid On/Off"))
  6201. grid_toggle.setCheckable(True)
  6202. if self.grid_status() == True:
  6203. grid_toggle.setChecked(True)
  6204. else:
  6205. grid_toggle.setChecked(False)
  6206. self.ui.cmenu_gridmenu.addSeparator()
  6207. for grid in sorted_list:
  6208. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  6209. action.triggered.connect(self.set_grid)
  6210. self.ui.cmenu_gridmenu.addSeparator()
  6211. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), _("Add"))
  6212. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), _("Delete"))
  6213. grid_add.triggered.connect(self.on_grid_add)
  6214. grid_delete.triggered.connect(self.on_grid_delete)
  6215. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  6216. def set_grid(self):
  6217. self.ui.grid_gap_x_entry.setText(self.sender().text())
  6218. self.ui.grid_gap_y_entry.setText(self.sender().text())
  6219. def on_grid_add(self):
  6220. # ## Current application units in lower Case
  6221. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6222. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  6223. text=_('Enter a Grid Value:'),
  6224. min=0.0000, max=99.9999, decimals=4)
  6225. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  6226. val, ok = grid_add_popup.get_value()
  6227. if ok:
  6228. if float(val) == 0:
  6229. self.inform.emit('[WARNING_NOTCL] %s' %
  6230. _("Please enter a grid value with non-zero value, in Float format."))
  6231. return
  6232. else:
  6233. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  6234. self.defaults["global_grid_context_menu"][str(units)].append(val)
  6235. self.inform.emit('[success] %s...' %
  6236. _("New Grid added"))
  6237. else:
  6238. self.inform.emit('[WARNING_NOTCL] %s...' %
  6239. _("Grid already exists"))
  6240. else:
  6241. self.inform.emit('[WARNING_NOTCL] %s...' %
  6242. _("Adding New Grid cancelled"))
  6243. def on_grid_delete(self):
  6244. # ## Current application units in lower Case
  6245. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().lower()
  6246. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  6247. text='Enter a Grid Value:',
  6248. min=0.0000, max=99.9999, decimals=4)
  6249. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  6250. val, ok = grid_del_popup.get_value()
  6251. if ok:
  6252. if float(val) == 0:
  6253. self.inform.emit('[WARNING_NOTCL] %s' %
  6254. _("Please enter a grid value with non-zero value, in Float format."))
  6255. return
  6256. else:
  6257. try:
  6258. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  6259. except ValueError:
  6260. self.inform.emit('[ERROR_NOTCL]%s...' %
  6261. _(" Grid Value does not exist"))
  6262. return
  6263. self.inform.emit('[success] %s...' %
  6264. _("Grid Value deleted"))
  6265. else:
  6266. self.inform.emit('[WARNING_NOTCL] %s...' %
  6267. _("Delete Grid value cancelled"))
  6268. def on_shortcut_list(self):
  6269. self.report_usage("on_shortcut_list()")
  6270. # add the tab if it was closed
  6271. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  6272. # delete the absolute and relative position and messages in the infobar
  6273. self.ui.position_label.setText("")
  6274. self.ui.rel_position_label.setText("")
  6275. # Switch plot_area to preferences page
  6276. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  6277. # self.ui.show()
  6278. def on_select_tab(self, name):
  6279. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  6280. if self.ui.splitter.sizes()[0] == 0:
  6281. self.ui.splitter.setSizes([1, 1])
  6282. else:
  6283. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  6284. self.ui.splitter.setSizes([0, 1])
  6285. if name == 'project':
  6286. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6287. elif name == 'selected':
  6288. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6289. elif name == 'tool':
  6290. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  6291. def on_copy_name(self):
  6292. self.report_usage("on_copy_name()")
  6293. obj = self.collection.get_active()
  6294. try:
  6295. name = obj.options["name"]
  6296. except AttributeError:
  6297. log.debug("on_copy_name() --> No object selected to copy it's name")
  6298. self.inform.emit('[WARNING_NOTCL]%s' %
  6299. _(" No object selected to copy it's name"))
  6300. return
  6301. self.clipboard.setText(name)
  6302. self.inform.emit(_("Name copied on clipboard ..."))
  6303. def on_mouse_click_over_plot(self, event):
  6304. """
  6305. Default actions are:
  6306. :param event: Contains information about the event, like which button
  6307. was clicked, the pixel coordinates and the axes coordinates.
  6308. :return: None
  6309. """
  6310. self.pos = []
  6311. if self.is_legacy is False:
  6312. event_pos = event.pos
  6313. if self.defaults["global_pan_button"] == '2':
  6314. pan_button = 2
  6315. else:
  6316. pan_button = 3
  6317. # Set the mouse button for panning
  6318. self.plotcanvas.view.camera.pan_button_setting = pan_button
  6319. else:
  6320. event_pos = (event.xdata, event.ydata)
  6321. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6322. if self.defaults["global_pan_button"] == '2':
  6323. pan_button = 3
  6324. else:
  6325. pan_button = 2
  6326. # So it can receive key presses
  6327. self.plotcanvas.native.setFocus()
  6328. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6329. if self.grid_status() == True:
  6330. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  6331. else:
  6332. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  6333. try:
  6334. modifiers = QtWidgets.QApplication.keyboardModifiers()
  6335. if event.button == 1:
  6336. # Reset here the relative coordinates so there is a new reference on the click position
  6337. if self.rel_point1 is None:
  6338. self.rel_point1 = self.pos
  6339. else:
  6340. self.rel_point2 = copy(self.rel_point1)
  6341. self.rel_point1 = self.pos
  6342. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  6343. if modifiers == QtCore.Qt.ShiftModifier:
  6344. # do not auto open the Project Tab
  6345. self.click_noproject = True
  6346. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  6347. self.inform.emit('[success] %s' %
  6348. _("Coordinates copied to clipboard."))
  6349. return
  6350. self.on_mouse_move_over_plot(event, origin_click=True)
  6351. except Exception as e:
  6352. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  6353. def on_double_click_over_plot(self, event):
  6354. if event.button == 1:
  6355. self.doubleclick = True
  6356. def on_mouse_move_over_plot(self, event, origin_click=None):
  6357. """
  6358. Callback for the mouse motion event over the plot.
  6359. :param event: Contains information about the event.
  6360. :param origin_click
  6361. :return: None
  6362. """
  6363. if self.is_legacy is False:
  6364. event_pos = event.pos
  6365. if self.defaults["global_pan_button"] == '2':
  6366. pan_button = 2
  6367. else:
  6368. pan_button = 3
  6369. event_is_dragging = event.is_dragging
  6370. else:
  6371. event_pos = (event.xdata, event.ydata)
  6372. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6373. if self.defaults["global_pan_button"] == '2':
  6374. pan_button = 3
  6375. else:
  6376. pan_button = 2
  6377. event_is_dragging = self.plotcanvas.is_dragging
  6378. # So it can receive key presses
  6379. self.plotcanvas.native.setFocus()
  6380. self.pos_jump = event_pos
  6381. self.ui.popMenu.mouse_is_panning = False
  6382. if not origin_click:
  6383. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  6384. if event.button == pan_button and event_is_dragging == 1:
  6385. self.ui.popMenu.mouse_is_panning = True
  6386. return
  6387. if self.rel_point1 is not None:
  6388. try: # May fail in case mouse not within axes
  6389. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6390. if self.grid_status() == True:
  6391. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6392. if self.is_legacy is False:
  6393. # Update cursor
  6394. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  6395. symbol='++', edge_color='black', size=20)
  6396. else:
  6397. self.app_cursor.set_data((pos[0], pos[1]))
  6398. else:
  6399. pos = (pos_canvas[0], pos_canvas[1])
  6400. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6401. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  6402. dx = pos[0] - self.rel_point1[0]
  6403. dy = pos[1] - self.rel_point1[1]
  6404. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6405. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6406. self.mouse = [pos[0], pos[1]]
  6407. # if the mouse is moved and the LMB is clicked then the action is a selection
  6408. if event_is_dragging == 1 and event.button == 1:
  6409. self.delete_selection_shape()
  6410. if dx < 0:
  6411. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  6412. face_color=self.defaults['global_alt_sel_fill'])
  6413. self.selection_type = False
  6414. else:
  6415. self.draw_moving_selection_shape(self.pos, pos)
  6416. self.selection_type = True
  6417. # hover effect - enabled in Preferences -> General -> GUI Settings
  6418. if self.defaults['global_hover']:
  6419. for obj in self.collection.get_list():
  6420. try:
  6421. # select the object(s) only if it is enabled (plotted)
  6422. if obj.options['plot']:
  6423. if obj not in self.collection.get_selected():
  6424. poly_obj = Polygon(
  6425. [(obj.options['xmin'], obj.options['ymin']),
  6426. (obj.options['xmax'], obj.options['ymin']),
  6427. (obj.options['xmax'], obj.options['ymax']),
  6428. (obj.options['xmin'], obj.options['ymax'])]
  6429. )
  6430. if Point(pos).within(poly_obj):
  6431. if obj.isHovering is False:
  6432. obj.isHovering = True
  6433. obj.notHovering = True
  6434. # create the selection box around the selected object
  6435. self.draw_hover_shape(obj, color='#d1e0e0')
  6436. else:
  6437. if obj.notHovering is True:
  6438. obj.notHovering = False
  6439. obj.isHovering = False
  6440. self.delete_hover_shape()
  6441. except:
  6442. # the Exception here will happen if we try to select on screen and we have an
  6443. # newly (and empty) just created Geometry or Excellon object that do not have the
  6444. # xmin, xmax, ymin, ymax options.
  6445. # In this case poly_obj creation (see above) will fail
  6446. pass
  6447. except:
  6448. self.ui.position_label.setText("")
  6449. self.ui.rel_position_label.setText("")
  6450. self.mouse = None
  6451. def on_mouse_click_release_over_plot(self, event):
  6452. """
  6453. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  6454. and has been registered in ''self.__init__()''.
  6455. :param event: contains information about the event.
  6456. :return:
  6457. """
  6458. pos = 0, 0
  6459. if self.is_legacy is False:
  6460. event_pos = event.pos
  6461. right_button = 2
  6462. else:
  6463. event_pos = (event.xdata, event.ydata)
  6464. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  6465. right_button = 3
  6466. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6467. if self.grid_status() == True:
  6468. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6469. else:
  6470. pos = (pos_canvas[0], pos_canvas[1])
  6471. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  6472. # canvas menu
  6473. if event.button == right_button: # right click
  6474. if self.ui.popMenu.mouse_is_panning is False:
  6475. self.cursor = QtGui.QCursor()
  6476. self.populate_cmenu_grids()
  6477. self.ui.popMenu.popup(self.cursor.pos())
  6478. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  6479. # selection and then select a type of selection ("enclosing" or "touching")
  6480. try:
  6481. if event.button == 1: # left click
  6482. if self.doubleclick is True:
  6483. self.doubleclick = False
  6484. if self.collection.get_selected():
  6485. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6486. if self.ui.splitter.sizes()[0] == 0:
  6487. self.ui.splitter.setSizes([1, 1])
  6488. # delete the selection shape(S) as it may be in the way
  6489. self.delete_selection_shape()
  6490. self.delete_hover_shape()
  6491. else:
  6492. if self.selection_type is not None:
  6493. self.selection_area_handler(self.pos, pos, self.selection_type)
  6494. self.selection_type = None
  6495. else:
  6496. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  6497. if key_modifier == QtCore.Qt.ShiftModifier:
  6498. mod_key = 'Shift'
  6499. elif key_modifier == QtCore.Qt.ControlModifier:
  6500. mod_key = 'Control'
  6501. else:
  6502. mod_key = None
  6503. if mod_key == self.defaults["global_mselect_key"]:
  6504. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  6505. # deselect, and if it's not selected then it will be selected
  6506. # If there is no active command (self.command_active is None) then we check if we clicked
  6507. # on a object by checking the bounding limits against mouse click position
  6508. if self.command_active is None:
  6509. self.select_objects(key='CTRL')
  6510. self.delete_hover_shape()
  6511. else:
  6512. # If there is no active command (self.command_active is None) then we check if we clicked
  6513. # on a object by checking the bounding limits against mouse click position
  6514. if self.command_active is None:
  6515. self.select_objects()
  6516. self.delete_hover_shape()
  6517. except Exception as e:
  6518. log.warning("Error: %s" % str(e))
  6519. return
  6520. def selection_area_handler(self, start_pos, end_pos, sel_type):
  6521. """
  6522. :param start_pos: mouse position when the selection LMB click was done
  6523. :param end_pos: mouse position when the left mouse button is released
  6524. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  6525. :return:
  6526. """
  6527. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  6528. self.delete_selection_shape()
  6529. for obj in self.collection.get_list():
  6530. try:
  6531. # select the object(s) only if it is enabled (plotted)
  6532. if obj.options['plot']:
  6533. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  6534. (obj.options['xmax'], obj.options['ymin']),
  6535. (obj.options['xmax'], obj.options['ymax']),
  6536. (obj.options['xmin'], obj.options['ymax'])])
  6537. if sel_type is True:
  6538. if poly_obj.within(poly_selection):
  6539. # create the selection box around the selected object
  6540. if self.defaults['global_selection_shape'] is True:
  6541. self.draw_selection_shape(obj)
  6542. self.collection.set_active(obj.options['name'])
  6543. else:
  6544. if poly_selection.intersects(poly_obj):
  6545. # create the selection box around the selected object
  6546. if self.defaults['global_selection_shape'] is True:
  6547. self.draw_selection_shape(obj)
  6548. self.collection.set_active(obj.options['name'])
  6549. except Exception as e:
  6550. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  6551. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  6552. # In this case poly_obj creation (see above) will fail
  6553. log.debug("App.selection_area_handler() --> %s" % str(e))
  6554. def select_objects(self, key=None):
  6555. # list where we store the overlapped objects under our mouse left click position
  6556. objects_under_the_click_list = []
  6557. # Populate the list with the overlapped objects on the click position
  6558. curr_x, curr_y = self.pos
  6559. for obj in self.all_objects_list:
  6560. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  6561. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  6562. if obj.options['name'] not in objects_under_the_click_list:
  6563. if obj.options['plot']:
  6564. # add objects to the objects_under_the_click list only if the object is plotted
  6565. # (active and not disabled)
  6566. objects_under_the_click_list.append(obj.options['name'])
  6567. try:
  6568. # If there is no element in the overlapped objects list then make everyone inactive
  6569. # because we selected "nothing"
  6570. if not objects_under_the_click_list:
  6571. self.collection.set_all_inactive()
  6572. # delete the possible selection box around a possible selected object
  6573. self.delete_selection_shape()
  6574. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  6575. # only when working on App
  6576. if self.call_source == 'app':
  6577. if self.click_noproject is False:
  6578. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6579. else:
  6580. # restore auto open the Project Tab
  6581. self.click_noproject = False
  6582. # delete any text in the status bar, implicitly the last object name that was selected
  6583. self.inform.emit("")
  6584. else:
  6585. self.call_source = 'app'
  6586. else:
  6587. # case when there is only an object under the click and we toggle it
  6588. if len(objects_under_the_click_list) == 1:
  6589. if self.collection.get_active() is None:
  6590. self.collection.set_active(objects_under_the_click_list[0])
  6591. # create the selection box around the selected object
  6592. curr_sel_obj = self.collection.get_active()
  6593. if self.defaults['global_selection_shape'] is True:
  6594. self.draw_selection_shape(curr_sel_obj)
  6595. # self.inform.emit('[selected] %s: %s selected' %
  6596. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6597. if curr_sel_obj.kind == 'gerber':
  6598. self.inform.emit(
  6599. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6600. color='green', name=str(curr_sel_obj.options['name'])))
  6601. elif curr_sel_obj.kind == 'excellon':
  6602. self.inform.emit(
  6603. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6604. color='brown', name=str(curr_sel_obj.options['name'])))
  6605. elif curr_sel_obj.kind == 'cncjob':
  6606. self.inform.emit(
  6607. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6608. color='blue', name=str(curr_sel_obj.options['name'])))
  6609. elif curr_sel_obj.kind == 'geometry':
  6610. self.inform.emit(
  6611. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6612. color='red', name=str(curr_sel_obj.options['name'])))
  6613. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  6614. self.collection.set_all_inactive()
  6615. self.delete_selection_shape()
  6616. self.collection.set_active(objects_under_the_click_list[0])
  6617. # create the selection box around the selected object
  6618. curr_sel_obj = self.collection.get_active()
  6619. if self.defaults['global_selection_shape'] is True:
  6620. self.draw_selection_shape(curr_sel_obj)
  6621. # self.inform.emit('[selected] %s: %s selected' %
  6622. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6623. if curr_sel_obj.kind == 'gerber':
  6624. self.inform.emit(
  6625. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6626. color='green', name=str(curr_sel_obj.options['name'])))
  6627. elif curr_sel_obj.kind == 'excellon':
  6628. self.inform.emit(
  6629. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6630. color='brown', name=str(curr_sel_obj.options['name'])))
  6631. elif curr_sel_obj.kind == 'cncjob':
  6632. self.inform.emit(
  6633. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6634. color='blue', name=str(curr_sel_obj.options['name'])))
  6635. elif curr_sel_obj.kind == 'geometry':
  6636. self.inform.emit(
  6637. _('[selected]<span style="color:{color};">{name}</span> selected').format(
  6638. color='red', name=str(curr_sel_obj.options['name'])))
  6639. else:
  6640. self.collection.set_all_inactive()
  6641. self.delete_selection_shape()
  6642. if self.call_source == 'app':
  6643. # delete any text in the status bar, implicitly the last object name that was selected
  6644. self.inform.emit("")
  6645. else:
  6646. self.call_source = 'app'
  6647. else:
  6648. # If there is no selected object
  6649. # make active the first element of the overlapped objects list
  6650. if self.collection.get_active() is None:
  6651. self.collection.set_active(objects_under_the_click_list[0])
  6652. name_sel_obj = self.collection.get_active().options['name']
  6653. # In case that there is a selected object but it is not in the overlapped object list
  6654. # make that object inactive and activate the first element in the overlapped object list
  6655. if name_sel_obj not in objects_under_the_click_list:
  6656. self.collection.set_inactive(name_sel_obj)
  6657. name_sel_obj = objects_under_the_click_list[0]
  6658. self.collection.set_active(name_sel_obj)
  6659. else:
  6660. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  6661. self.collection.set_all_inactive()
  6662. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  6663. len(objects_under_the_click_list)])
  6664. curr_sel_obj = self.collection.get_active()
  6665. # delete the possible selection box around a possible selected object
  6666. self.delete_selection_shape()
  6667. # create the selection box around the selected object
  6668. if self.defaults['global_selection_shape'] is True:
  6669. self.draw_selection_shape(curr_sel_obj)
  6670. # self.inform.emit('[selected] %s: %s selected' %
  6671. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  6672. if curr_sel_obj.kind == 'gerber':
  6673. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6674. color='green', name=str(curr_sel_obj.options['name'])))
  6675. elif curr_sel_obj.kind == 'excellon':
  6676. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6677. color='brown', name=str(curr_sel_obj.options['name'])))
  6678. elif curr_sel_obj.kind == 'cncjob':
  6679. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6680. color='blue', name=str(curr_sel_obj.options['name'])))
  6681. elif curr_sel_obj.kind == 'geometry':
  6682. self.inform.emit(_('[selected]<span style="color:{color};">{name}</span> selected').format(
  6683. color='red', name=str(curr_sel_obj.options['name'])))
  6684. # for obj in self.collection.get_list():
  6685. # obj.plot()
  6686. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  6687. # TODO: on selected objects change the object colors and do not draw the selection box
  6688. # self.plotcanvas.update() # this updates the canvas
  6689. except Exception as e:
  6690. log.error("[ERROR] Something went bad. %s" % str(e))
  6691. return
  6692. def delete_hover_shape(self):
  6693. self.hover_shapes.clear()
  6694. self.hover_shapes.redraw()
  6695. def draw_hover_shape(self, sel_obj, color=None):
  6696. """
  6697. :param sel_obj: the object for which the hover shape must be drawn
  6698. :return:
  6699. """
  6700. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6701. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6702. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6703. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6704. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  6705. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6706. hover_rect = hover_rect.buffer(-0.1)
  6707. hover_rect = hover_rect.buffer(0.2)
  6708. else:
  6709. hover_rect = hover_rect.buffer(-0.00393)
  6710. hover_rect = hover_rect.buffer(0.00787)
  6711. if color:
  6712. face = Color(color)
  6713. face.alpha = 0.2
  6714. outline = Color(color, alpha=0.8)
  6715. else:
  6716. face = Color(self.defaults['global_sel_fill'])
  6717. face.alpha = 0.2
  6718. outline = self.defaults['global_sel_line']
  6719. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  6720. def delete_selection_shape(self):
  6721. self.move_tool.sel_shapes.clear()
  6722. self.move_tool.sel_shapes.redraw()
  6723. def draw_selection_shape(self, sel_obj, color=None):
  6724. """
  6725. :param sel_obj: the object for which the selection shape must be drawn
  6726. :return:
  6727. """
  6728. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6729. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6730. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6731. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6732. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6733. if self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper() == 'MM':
  6734. sel_rect = sel_rect.buffer(-0.1)
  6735. sel_rect = sel_rect.buffer(0.2)
  6736. else:
  6737. sel_rect = sel_rect.buffer(-0.00393)
  6738. sel_rect = sel_rect.buffer(0.00787)
  6739. if color:
  6740. face = Color(color, alpha=0.2)
  6741. outline = Color(color, alpha=0.8)
  6742. else:
  6743. face = Color(self.defaults['global_sel_fill'], alpha=0.2)
  6744. outline = Color(self.defaults['global_sel_line'], alpha=0.8)
  6745. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6746. color=outline,
  6747. face_color=face,
  6748. update=True,
  6749. layer=0,
  6750. tolerance=None))
  6751. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6752. """
  6753. :param old_coords: old coordinates
  6754. :param coords: new coordinates
  6755. :return:
  6756. """
  6757. if 'color' in kwargs:
  6758. color = kwargs['color']
  6759. else:
  6760. color = self.defaults['global_sel_line']
  6761. if 'face_color' in kwargs:
  6762. face_color = kwargs['face_color']
  6763. else:
  6764. face_color = self.defaults['global_sel_fill']
  6765. if 'face_alpha' in kwargs:
  6766. face_alpha = kwargs['face_alpha']
  6767. else:
  6768. face_alpha = 0.3
  6769. x0, y0 = old_coords
  6770. x1, y1 = coords
  6771. pt1 = (x0, y0)
  6772. pt2 = (x1, y0)
  6773. pt3 = (x1, y1)
  6774. pt4 = (x0, y1)
  6775. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6776. color_t = Color(face_color)
  6777. color_t.alpha = face_alpha
  6778. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6779. layer=0, tolerance=None)
  6780. def on_file_new_click(self):
  6781. if self.collection.get_list() and self.should_we_save:
  6782. msgbox = QtWidgets.QMessageBox()
  6783. # msgbox.setText("<B>Save changes ...</B>")
  6784. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6785. "Creating a New project will delete them.\n"
  6786. "Do you want to Save the project?"))
  6787. msgbox.setWindowTitle(_("Save changes"))
  6788. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  6789. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6790. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6791. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6792. msgbox.setDefaultButton(bt_yes)
  6793. msgbox.exec_()
  6794. response = msgbox.clickedButton()
  6795. if response == bt_yes:
  6796. self.on_file_saveprojectas()
  6797. elif response == bt_cancel:
  6798. return
  6799. elif response == bt_no:
  6800. self.on_file_new()
  6801. else:
  6802. self.on_file_new()
  6803. self.inform.emit('[success] %s...' %
  6804. _("New Project created"))
  6805. def on_file_new(self, cli=None):
  6806. """
  6807. Callback for menu item File->New. Returns the application to its
  6808. startup state. This method is thread-safe.
  6809. :return: None
  6810. """
  6811. self.report_usage("on_file_new")
  6812. # Remove everything from memory
  6813. App.log.debug("on_file_new()")
  6814. if self.call_source != 'app':
  6815. self.editor2object(cleanup=True)
  6816. # ## EDITOR section
  6817. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  6818. self.exc_editor = FlatCAMExcEditor(self)
  6819. self.grb_editor = FlatCAMGrbEditor(self)
  6820. # Clear pool
  6821. self.clear_pool()
  6822. for obj in self.collection.get_list():
  6823. # delete shapes left drawn from mark shape_collections, if any
  6824. if isinstance(obj, FlatCAMGerber):
  6825. try:
  6826. obj.mark_shapes.enabled = False
  6827. obj.mark_shapes.clear(update=True)
  6828. except AttributeError:
  6829. pass
  6830. # also delete annotation shapes, if any
  6831. elif isinstance(obj, FlatCAMCNCjob):
  6832. try:
  6833. obj.annotation.enabled = False
  6834. obj.annotation.clear(update=True)
  6835. except AttributeError:
  6836. pass
  6837. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6838. self.init_tcl()
  6839. self.delete_selection_shape()
  6840. self.collection.delete_all()
  6841. self.setup_component_editor()
  6842. # Clear project filename
  6843. self.project_filename = None
  6844. # Load the application defaults
  6845. self.load_defaults(filename='current_defaults')
  6846. # Re-fresh project options
  6847. self.on_options_app2project()
  6848. # Init Tools
  6849. self.init_tools()
  6850. if cli is None:
  6851. # Close any Tabs opened in the Plot Tab Area section
  6852. for index in range(self.ui.plot_tab_area.count()):
  6853. self.ui.plot_tab_area.closeTab(index)
  6854. # for whatever reason previous command does not close the last tab so I do it manually
  6855. self.ui.plot_tab_area.closeTab(0)
  6856. # # And then add again the Plot Area
  6857. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6858. self.ui.plot_tab_area.protectTab(0)
  6859. # take the focus of the Notebook on Project Tab.
  6860. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6861. self.set_ui_title(name=_("New Project - Not saved"))
  6862. def obj_properties(self):
  6863. self.report_usage("obj_properties()")
  6864. self.properties_tool.run(toggle=False)
  6865. def on_project_context_save(self):
  6866. obj = self.collection.get_active()
  6867. if type(obj) == FlatCAMGeometry:
  6868. self.on_file_exportdxf()
  6869. elif type(obj) == FlatCAMExcellon:
  6870. self.on_file_saveexcellon()
  6871. elif type(obj) == FlatCAMCNCjob:
  6872. obj.on_exportgcode_button_click()
  6873. elif type(obj) == FlatCAMGerber:
  6874. self.on_file_savegerber()
  6875. def obj_move(self):
  6876. self.report_usage("obj_move()")
  6877. self.move_tool.run(toggle=False)
  6878. def on_fileopengerber(self, checked=None, name=None):
  6879. """
  6880. File menu callback for opening a Gerber.
  6881. :return: None
  6882. """
  6883. self.report_usage("on_fileopengerber")
  6884. App.log.debug("on_fileopengerber()")
  6885. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6886. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6887. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  6888. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6889. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6890. "*.mil);;" \
  6891. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6892. "Allegro Files (*.art);;" \
  6893. "Mentor Files (*.pho *.gdo);;" \
  6894. "All Files (*.*)"
  6895. if name is None:
  6896. try:
  6897. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6898. directory=self.get_last_folder(),
  6899. filter=_filter_)
  6900. except TypeError:
  6901. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6902. filenames = [str(filename) for filename in filenames]
  6903. else:
  6904. filenames = [name]
  6905. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6906. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6907. _("Opening Gerber file.")),
  6908. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6909. color=QtGui.QColor("gray"))
  6910. if len(filenames) == 0:
  6911. self.inform.emit('[WARNING_NOTCL] %s' %
  6912. _("Open Gerber cancelled."))
  6913. else:
  6914. for filename in filenames:
  6915. if filename != '':
  6916. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6917. def on_fileopenexcellon(self, checked=None, name=None):
  6918. """
  6919. File menu callback for opening an Excellon file.
  6920. :return: None
  6921. """
  6922. self.report_usage("on_fileopenexcellon")
  6923. App.log.debug("on_fileopenexcellon()")
  6924. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6925. "All Files (*.*)"
  6926. if name is None:
  6927. try:
  6928. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6929. directory=self.get_last_folder(),
  6930. filter=_filter_)
  6931. except TypeError:
  6932. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6933. filenames = [str(filename) for filename in filenames]
  6934. else:
  6935. filenames = [str(name)]
  6936. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6937. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6938. _("Opening Excellon file.")),
  6939. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6940. color=QtGui.QColor("gray"))
  6941. if len(filenames) == 0:
  6942. self.inform.emit('[WARNING_NOTCL]%s' %
  6943. _(" Open Excellon cancelled."))
  6944. else:
  6945. for filename in filenames:
  6946. if filename != '':
  6947. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6948. def on_fileopengcode(self, checked=None, name=None):
  6949. """
  6950. File menu call back for opening gcode.
  6951. :return: None
  6952. """
  6953. self.report_usage("on_fileopengcode")
  6954. App.log.debug("on_fileopengcode()")
  6955. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6956. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6957. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  6958. "All Files (*.*)"
  6959. if name is None:
  6960. try:
  6961. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6962. directory=self.get_last_folder(),
  6963. filter=_filter_)
  6964. except TypeError:
  6965. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6966. filenames = [str(filename) for filename in filenames]
  6967. else:
  6968. filenames = [name]
  6969. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6970. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6971. _("Opening G-Code file.")),
  6972. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6973. color=QtGui.QColor("gray"))
  6974. if len(filenames) == 0:
  6975. self.inform.emit('[WARNING_NOTCL] %s' %
  6976. _("Open G-Code cancelled."))
  6977. else:
  6978. for filename in filenames:
  6979. if filename != '':
  6980. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename]})
  6981. def on_file_openproject(self, checked=None):
  6982. """
  6983. File menu callback for opening a project.
  6984. :return: None
  6985. """
  6986. self.report_usage("on_file_openproject")
  6987. App.log.debug("on_file_openproject()")
  6988. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6989. try:
  6990. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6991. directory=self.get_last_folder(), filter=_filter_)
  6992. except TypeError:
  6993. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6994. # The Qt methods above will return a QString which can cause problems later.
  6995. # So far json.dump() will fail to serialize it.
  6996. # TODO: Improve the serialization methods and remove this fix.
  6997. filename = str(filename)
  6998. if filename == "":
  6999. self.inform.emit('[WARNING_NOTCL] %s' %
  7000. _("Open Project cancelled."))
  7001. else:
  7002. # self.worker_task.emit({'fcn': self.open_project,
  7003. # 'params': [filename]})
  7004. # The above was failing because open_project() is not
  7005. # thread safe. The new_project()
  7006. self.open_project(filename)
  7007. def on_file_openconfig(self, checked=None):
  7008. """
  7009. File menu callback for opening a config file.
  7010. :return: None
  7011. """
  7012. self.report_usage("on_file_openconfig")
  7013. App.log.debug("on_file_openconfig()")
  7014. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7015. try:
  7016. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7017. directory=self.data_path, filter=_filter_)
  7018. except TypeError:
  7019. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7020. filter=_filter_)
  7021. if filename == "":
  7022. self.inform.emit('[WARNING_NOTCL] %s' %
  7023. _("Open Config cancelled."))
  7024. else:
  7025. self.open_config_file(filename)
  7026. def on_file_exportsvg(self):
  7027. """
  7028. Callback for menu item File->Export SVG.
  7029. :return: None
  7030. """
  7031. self.report_usage("on_file_exportsvg")
  7032. App.log.debug("on_file_exportsvg()")
  7033. obj = self.collection.get_active()
  7034. if obj is None:
  7035. self.inform.emit('[WARNING_NOTCL] %s' %
  7036. _("No object selected."))
  7037. msg = _("Please Select a Geometry object to export")
  7038. msgbox = QtWidgets.QMessageBox()
  7039. msgbox.setInformativeText(msg)
  7040. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7041. msgbox.setDefaultButton(bt_ok)
  7042. msgbox.exec_()
  7043. return
  7044. # Check for more compatible types and add as required
  7045. if (not isinstance(obj, FlatCAMGeometry)
  7046. and not isinstance(obj, FlatCAMGerber)
  7047. and not isinstance(obj, FlatCAMCNCjob)
  7048. and not isinstance(obj, FlatCAMExcellon)):
  7049. msg = '[ERROR_NOTCL] %s' % \
  7050. _("Only Geometry, Gerber and CNCJob objects can be used.")
  7051. msgbox = QtWidgets.QMessageBox()
  7052. msgbox.setInformativeText(msg)
  7053. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7054. msgbox.setDefaultButton(bt_ok)
  7055. msgbox.exec_()
  7056. return
  7057. name = obj.options["name"]
  7058. _filter = "SVG File (*.svg);;All Files (*.*)"
  7059. try:
  7060. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7061. caption=_("Export SVG"),
  7062. directory=self.get_last_save_folder() + '/' + str(name),
  7063. filter=_filter)
  7064. except TypeError:
  7065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  7066. filename = str(filename)
  7067. if filename == "":
  7068. self.inform.emit('[WARNING_NOTCL]%s' %
  7069. _(" Export SVG cancelled."))
  7070. return
  7071. else:
  7072. self.export_svg(name, filename)
  7073. if self.defaults["global_open_style"] is False:
  7074. self.file_opened.emit("SVG", filename)
  7075. self.file_saved.emit("SVG", filename)
  7076. def on_file_exportpng(self):
  7077. self.report_usage("on_file_exportpng")
  7078. App.log.debug("on_file_exportpng()")
  7079. self.date = str(datetime.today()).rpartition('.')[0]
  7080. self.date = ''.join(c for c in self.date if c not in ':-')
  7081. self.date = self.date.replace(' ', '_')
  7082. image = _screenshot()
  7083. data = np.asarray(image)
  7084. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  7085. self.inform.emit('[[WARNING_NOTCL]] %s' %
  7086. _('Data must be a 3D array with last dimension 3 or 4'))
  7087. return
  7088. filter_ = "PNG File (*.png);;All Files (*.*)"
  7089. try:
  7090. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7091. caption=_("Export PNG Image"),
  7092. directory=self.get_last_save_folder() + '/png_' + self.date,
  7093. filter=filter_)
  7094. except TypeError:
  7095. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  7096. filename = str(filename)
  7097. if filename == "":
  7098. self.inform.emit(_("Export PNG cancelled."))
  7099. return
  7100. else:
  7101. write_png(filename, data)
  7102. if self.defaults["global_open_style"] is False:
  7103. self.file_opened.emit("png", filename)
  7104. self.file_saved.emit("png", filename)
  7105. def on_file_savegerber(self):
  7106. """
  7107. Callback for menu item in Project context menu.
  7108. :return: None
  7109. """
  7110. self.report_usage("on_file_savegerber")
  7111. App.log.debug("on_file_savegerber()")
  7112. obj = self.collection.get_active()
  7113. if obj is None:
  7114. self.inform.emit('[WARNING_NOTCL] %s' %
  7115. _("No object selected. Please select an Gerber object to export."))
  7116. return
  7117. # Check for more compatible types and add as required
  7118. if not isinstance(obj, FlatCAMGerber):
  7119. self.inform.emit('[ERROR_NOTCL] %s' %
  7120. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7121. return
  7122. name = self.collection.get_active().options["name"]
  7123. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  7124. try:
  7125. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7126. caption="Save Gerber source file",
  7127. directory=self.get_last_save_folder() + '/' + name,
  7128. filter=_filter)
  7129. except TypeError:
  7130. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  7131. filename = str(filename)
  7132. if filename == "":
  7133. self.inform.emit('[WARNING_NOTCL] %s' %
  7134. _("Save Gerber source file cancelled."))
  7135. return
  7136. else:
  7137. self.save_source_file(name, filename)
  7138. if self.defaults["global_open_style"] is False:
  7139. self.file_opened.emit("Gerber", filename)
  7140. self.file_saved.emit("Gerber", filename)
  7141. def on_file_saveexcellon(self):
  7142. """
  7143. Callback for menu item in project context menu.
  7144. :return: None
  7145. """
  7146. self.report_usage("on_file_saveexcellon")
  7147. App.log.debug("on_file_saveexcellon()")
  7148. obj = self.collection.get_active()
  7149. if obj is None:
  7150. self.inform.emit('[WARNING_NOTCL] %s' %
  7151. _("No object selected. Please select an Excellon object to export."))
  7152. return
  7153. # Check for more compatible types and add as required
  7154. if not isinstance(obj, FlatCAMExcellon):
  7155. self.inform.emit('[ERROR_NOTCL] %s' %
  7156. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7157. return
  7158. name = self.collection.get_active().options["name"]
  7159. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7160. try:
  7161. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7162. caption=_("Save Excellon source file"),
  7163. directory=self.get_last_save_folder() + '/' + name,
  7164. filter=_filter)
  7165. except TypeError:
  7166. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  7167. filename = str(filename)
  7168. if filename == "":
  7169. self.inform.emit('[WARNING_NOTCL] %s' %
  7170. _("Saving Excellon source file cancelled."))
  7171. return
  7172. else:
  7173. self.save_source_file(name, filename)
  7174. if self.defaults["global_open_style"] is False:
  7175. self.file_opened.emit("Excellon", filename)
  7176. self.file_saved.emit("Excellon", filename)
  7177. def on_file_exportexcellon(self):
  7178. """
  7179. Callback for menu item File->Export->Excellon.
  7180. :return: None
  7181. """
  7182. self.report_usage("on_file_exportexcellon")
  7183. App.log.debug("on_file_exportexcellon()")
  7184. obj = self.collection.get_active()
  7185. if obj is None:
  7186. self.inform.emit('[WARNING_NOTCL] %s' %
  7187. _("No object selected. Please Select an Excellon object to export."))
  7188. return
  7189. # Check for more compatible types and add as required
  7190. if not isinstance(obj, FlatCAMExcellon):
  7191. self.inform.emit('[ERROR_NOTCL] %s' %
  7192. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7193. return
  7194. name = self.collection.get_active().options["name"]
  7195. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  7196. try:
  7197. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7198. caption=_("Export Excellon"),
  7199. directory=self.get_last_save_folder() + '/' + name,
  7200. filter=_filter)
  7201. except TypeError:
  7202. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  7203. filename = str(filename)
  7204. if filename == "":
  7205. self.inform.emit('[WARNING_NOTCL] %s' %
  7206. _("Export Excellon cancelled."))
  7207. return
  7208. else:
  7209. self.export_excellon(name, filename)
  7210. if self.defaults["global_open_style"] is False:
  7211. self.file_opened.emit("Excellon", filename)
  7212. self.file_saved.emit("Excellon", filename)
  7213. def on_file_exportgerber(self):
  7214. """
  7215. Callback for menu item File->Export->Gerber.
  7216. :return: None
  7217. """
  7218. self.report_usage("on_file_exportgerber")
  7219. App.log.debug("on_file_exportgerber()")
  7220. obj = self.collection.get_active()
  7221. if obj is None:
  7222. self.inform.emit('[WARNING_NOTCL] %s' %
  7223. _("No object selected. Please Select an Gerber object to export."))
  7224. return
  7225. # Check for more compatible types and add as required
  7226. if not isinstance(obj, FlatCAMGerber):
  7227. self.inform.emit('[ERROR_NOTCL] %s' %
  7228. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  7229. return
  7230. name = self.collection.get_active().options["name"]
  7231. _filter_ = "Gerber File (*.GBR);;All Files (*.*)"
  7232. try:
  7233. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7234. caption=_("Export Gerber"),
  7235. directory=self.get_last_save_folder() + '/' + name,
  7236. filter=_filter_)
  7237. except TypeError:
  7238. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  7239. filename = str(filename)
  7240. if filename == "":
  7241. self.inform.emit('[WARNING_NOTCL] %s' %
  7242. _("Export Gerber cancelled."))
  7243. return
  7244. else:
  7245. self.export_gerber(name, filename)
  7246. if self.defaults["global_open_style"] is False:
  7247. self.file_opened.emit("Gerber", filename)
  7248. self.file_saved.emit("Gerber", filename)
  7249. def on_file_exportdxf(self):
  7250. """
  7251. Callback for menu item File->Export DXF.
  7252. :return: None
  7253. """
  7254. self.report_usage("on_file_exportdxf")
  7255. App.log.debug("on_file_exportdxf()")
  7256. obj = self.collection.get_active()
  7257. if obj is None:
  7258. self.inform.emit('[WARNING_NOTCL] %s' %
  7259. _("No object selected."))
  7260. msg = _("Please Select a Geometry object to export")
  7261. msgbox = QtWidgets.QMessageBox()
  7262. msgbox.setInformativeText(msg)
  7263. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7264. msgbox.setDefaultButton(bt_ok)
  7265. msgbox.exec_()
  7266. return
  7267. # Check for more compatible types and add as required
  7268. if not isinstance(obj, FlatCAMGeometry):
  7269. msg = '[ERROR_NOTCL] %s' % \
  7270. _("Only Geometry objects can be used.")
  7271. msgbox = QtWidgets.QMessageBox()
  7272. msgbox.setInformativeText(msg)
  7273. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  7274. msgbox.setDefaultButton(bt_ok)
  7275. msgbox.exec_()
  7276. return
  7277. name = self.collection.get_active().options["name"]
  7278. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7279. try:
  7280. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7281. caption=_("Export DXF"),
  7282. directory=self.get_last_save_folder() + '/' + name,
  7283. filter=_filter_)
  7284. except TypeError:
  7285. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  7286. filter=_filter_)
  7287. filename = str(filename)
  7288. if filename == "":
  7289. self.inform.emit('[WARNING_NOTCL] %s' %
  7290. _("Export DXF cancelled."))
  7291. return
  7292. else:
  7293. self.export_dxf(name, filename)
  7294. if self.defaults["global_open_style"] is False:
  7295. self.file_opened.emit("DXF", filename)
  7296. self.file_saved.emit("DXF", filename)
  7297. def on_file_importsvg(self, type_of_obj):
  7298. """
  7299. Callback for menu item File->Import SVG.
  7300. :param type_of_obj: to import the SVG as Geometry or as Gerber
  7301. :type type_of_obj: str
  7302. :return: None
  7303. """
  7304. self.report_usage("on_file_importsvg")
  7305. App.log.debug("on_file_importsvg()")
  7306. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  7307. try:
  7308. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7309. directory=self.get_last_folder(), filter=_filter_)
  7310. except TypeError:
  7311. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  7312. filter=_filter_)
  7313. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7314. type_of_obj = "geometry"
  7315. filenames = [str(filename) for filename in filenames]
  7316. if len(filenames) == 0:
  7317. self.inform.emit('[WARNING_NOTCL] %s' %
  7318. _("Open SVG cancelled."))
  7319. else:
  7320. for filename in filenames:
  7321. if filename != '':
  7322. self.worker_task.emit({'fcn': self.import_svg,
  7323. 'params': [filename, type_of_obj]})
  7324. def on_file_importdxf(self, type_of_obj):
  7325. """
  7326. Callback for menu item File->Import DXF.
  7327. :param type_of_obj: to import the DXF as Geometry or as Gerber
  7328. :type type_of_obj: str
  7329. :return: None
  7330. """
  7331. self.report_usage("on_file_importdxf")
  7332. App.log.debug("on_file_importdxf()")
  7333. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  7334. try:
  7335. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7336. directory=self.get_last_folder(),
  7337. filter=_filter_)
  7338. except TypeError:
  7339. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  7340. filter=_filter_)
  7341. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  7342. type_of_obj = "geometry"
  7343. filenames = [str(filename) for filename in filenames]
  7344. if len(filenames) == 0:
  7345. self.inform.emit('[WARNING_NOTCL] %s' %
  7346. _("Open DXF cancelled."))
  7347. else:
  7348. for filename in filenames:
  7349. if filename != '':
  7350. self.worker_task.emit({'fcn': self.import_dxf,
  7351. 'params': [filename, type_of_obj]})
  7352. # ###############################################################################################################
  7353. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  7354. # ###############################################################################################################
  7355. def init_code_editor(self, name):
  7356. # Signals section
  7357. # Disconnect the old signals
  7358. try:
  7359. self.ui.buttonOpen.clicked.disconnect()
  7360. except TypeError:
  7361. pass
  7362. try:
  7363. self.ui.buttonSave.clicked.disconnect()
  7364. except TypeError:
  7365. pass
  7366. # add the tab if it was closed
  7367. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, '%s' % name)
  7368. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  7369. # delete the absolute and relative position and messages in the infobar
  7370. self.ui.position_label.setText("")
  7371. self.ui.rel_position_label.setText("")
  7372. # first clear previous text in text editor (if any)
  7373. self.ui.code_editor.clear()
  7374. self.ui.code_editor.setReadOnly(False)
  7375. self.toggle_codeeditor = True
  7376. self.ui.code_editor.completer_enable = False
  7377. self.ui.buttonRun.hide()
  7378. # make sure to keep a reference to the code editor
  7379. self.reference_code_editor = self.ui.code_editor
  7380. # Switch plot_area to CNCJob tab
  7381. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  7382. def on_view_source(self):
  7383. self.inform.emit('%s' %
  7384. _("Viewing the source code of the selected object."))
  7385. self.proc_container.view.set_busy(_("Loading..."))
  7386. try:
  7387. obj = self.collection.get_active()
  7388. except Exception as e:
  7389. log.debug("App.on_view_source() --> %s" % str(e))
  7390. self.inform.emit('[WARNING_NOTCL] %s' %
  7391. _("Select an Gerber or Excellon file to view it's source file."))
  7392. return 'fail'
  7393. if obj.kind == 'gerber':
  7394. flt = "Gerber Files (*.GBR);;All Files (*.*)"
  7395. elif obj.kind == 'excellon':
  7396. flt = "Excellon Files (*.DRL);;All Files (*.*)"
  7397. elif obj.kind == 'cncjob':
  7398. "GCode Files (*.NC);;All Files (*.*)"
  7399. else:
  7400. flt = "All Files (*.*)"
  7401. self.init_code_editor(name=_("Source Editor"))
  7402. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7403. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7404. # then append the text from GCode to the text editor
  7405. if obj.kind == 'cncjob':
  7406. try:
  7407. file = obj.export_gcode(
  7408. preamble=self.defaults["cncjob_prepend"],
  7409. postamble=self.defaults["cncjob_append"],
  7410. to_file=True)
  7411. if file == 'fail':
  7412. return 'fail'
  7413. except AttributeError:
  7414. self.inform.emit('[WARNING_NOTCL] %s' %
  7415. _("There is no selected object for which to see it's source file code."))
  7416. return 'fail'
  7417. else:
  7418. try:
  7419. file = StringIO(obj.source_file)
  7420. except AttributeError:
  7421. self.inform.emit('[WARNING_NOTCL] %s' %
  7422. _("There is no selected object for which to see it's source file code."))
  7423. return 'fail'
  7424. self.ui.cncjob_frame.hide()
  7425. try:
  7426. for line in file:
  7427. QtWidgets.QApplication.processEvents()
  7428. proc_line = str(line).strip('\n')
  7429. self.ui.code_editor.append(proc_line)
  7430. except Exception as e:
  7431. log.debug('App.on_view_source() -->%s' % str(e))
  7432. self.inform.emit('[ERROR] %s: %s' %
  7433. (_('Failed to load the source code for the selected object'), str(e)))
  7434. return
  7435. self.handleTextChanged()
  7436. self.ui.cncjob_frame.show()
  7437. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7438. self.proc_container.view.set_idle()
  7439. # self.ui.show()
  7440. def on_toggle_code_editor(self):
  7441. self.report_usage("on_toggle_code_editor()")
  7442. if self.toggle_codeeditor is False:
  7443. self.init_code_editor(name=_("Code Editor"))
  7444. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen())
  7445. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode())
  7446. else:
  7447. for idx in range(self.ui.plot_tab_area.count()):
  7448. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  7449. self.ui.plot_tab_area.closeTab(idx)
  7450. break
  7451. self.toggle_codeeditor = False
  7452. def on_filenewscript(self, silent=False):
  7453. """
  7454. Will create a new script file and open it in the Code Editor
  7455. :param silent: if True will not display status messages
  7456. :return: None
  7457. """
  7458. if silent is False:
  7459. self.inform.emit('[success] %s' %
  7460. _("New TCL script file created in Code Editor."))
  7461. flt = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  7462. self.init_code_editor(name=_("Script Editor"))
  7463. self.ui.code_editor.completer_enable = True
  7464. self.ui.code_editor.append(_(
  7465. "#\n"
  7466. "# CREATE A NEW FLATCAM TCL SCRIPT\n"
  7467. "# TCL Tutorial here: https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n"
  7468. "#\n\n"
  7469. "# FlatCAM commands list:\n"
  7470. "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, AlignDrillGrid, ClearShell, ClearCopper,\n"
  7471. "# Cncjob, Cutout, Delete, Drillcncjob, ExportGcode, ExportSVG, Exteriors, GeoCutout, GeoUnion, GetNames,\n"
  7472. "# GetSys, ImportSvg, Interiors, Isolate, Follow, JoinExcellon, JoinGeometry, ListSys, MillDrills,\n"
  7473. "# MillSlots, Mirror, New, NewGeometry, Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"
  7474. "# Options, Paint, Panelize, Plot, SaveProject, SaveSys, Scale, SetActive, SetSys, Skew, SubtractPoly,\n"
  7475. "# SubtractRectangle, Version, WriteGCode\n"
  7476. "#\n\n"
  7477. ))
  7478. self.ui.buttonOpen.clicked.connect(lambda: self.handleOpen(filt=flt))
  7479. self.ui.buttonSave.clicked.connect(lambda: self.handleSaveGCode(filt=flt))
  7480. self.ui.buttonRun.show()
  7481. try:
  7482. self.ui.buttonRun.clicked.disconnect(self.handleRunCode)
  7483. except TypeError:
  7484. pass
  7485. self.ui.buttonRun.clicked.connect(self.handleRunCode)
  7486. self.handleTextChanged()
  7487. self.ui.code_editor.show()
  7488. def on_fileopenscript(self, name=None, silent=False):
  7489. """
  7490. Will open a Tcl script file into the Code Editor
  7491. :param silent: if True will not display status messages
  7492. :param name: name of a Tcl script file to open
  7493. :return:
  7494. """
  7495. if name:
  7496. filename = name
  7497. else:
  7498. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7499. try:
  7500. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"),
  7501. directory=self.get_last_folder(), filter=_filter_)
  7502. except TypeError:
  7503. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open TCL script"), filter=_filter_)
  7504. # The Qt methods above will return a QString which can cause problems later.
  7505. # So far json.dump() will fail to serialize it.
  7506. # TODO: Improve the serialization methods and remove this fix.
  7507. filename = str(filename)
  7508. if filename == "":
  7509. if silent is False:
  7510. self.inform.emit('[WARNING_NOTCL] %s' %
  7511. _("Open TCL script cancelled."))
  7512. else:
  7513. self.on_filenewscript()
  7514. try:
  7515. with open(filename, "r") as opened_script:
  7516. try:
  7517. for line in opened_script:
  7518. proc_line = str(line).strip('\n')
  7519. self.ui.code_editor.append(proc_line)
  7520. except Exception as e:
  7521. log.debug('App.on_fileopenscript() -->%s' % str(e))
  7522. if silent is False:
  7523. self.inform.emit('[ERROR] %s %s' %
  7524. (_('App.on_fileopenscript() -->'), str(e)))
  7525. return
  7526. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  7527. self.handleTextChanged()
  7528. if silent is False:
  7529. self.inform.emit('[success] %s' %
  7530. _("TCL script file opened in Code Editor."))
  7531. # self.ui.show()
  7532. except Exception as e:
  7533. log.debug("App.on_fileopenscript() -> %s" % str(e))
  7534. def on_filerunscript(self, name=None, silent=False):
  7535. """
  7536. File menu callback for loading and running a TCL script.
  7537. :param silent: if True will not display status messages
  7538. :param name: name of a Tcl script file to be run by FlatCAM
  7539. :return: None
  7540. """
  7541. self.report_usage("on_filerunscript")
  7542. App.log.debug("on_file_runscript()")
  7543. if name:
  7544. filename = name
  7545. if self.cmd_line_headless != 1:
  7546. self.splash.showMessage('%s: %ssec\n%s' %
  7547. (_("Canvas initialization started.\n"
  7548. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7549. _("Executing FlatCAMScript file.")
  7550. ),
  7551. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7552. color=QtGui.QColor("gray"))
  7553. else:
  7554. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  7555. try:
  7556. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  7557. directory=self.get_last_folder(), filter=_filter_)
  7558. except TypeError:
  7559. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  7560. # The Qt methods above will return a QString which can cause problems later.
  7561. # So far json.dump() will fail to serialize it.
  7562. # TODO: Improve the serialization methods and remove this fix.
  7563. filename = str(filename)
  7564. if filename == "":
  7565. if silent is False:
  7566. self.inform.emit('[WARNING_NOTCL] %s' %
  7567. _("Run TCL script cancelled."))
  7568. else:
  7569. if self.cmd_line_headless != 1:
  7570. if self.ui.shell_dock.isHidden():
  7571. self.ui.shell_dock.show()
  7572. try:
  7573. with open(filename, "r") as tcl_script:
  7574. cmd_line_shellfile_content = tcl_script.read()
  7575. if self.cmd_line_headless != 1:
  7576. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  7577. else:
  7578. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  7579. if silent is False:
  7580. self.inform.emit('[success] %s' %
  7581. _("TCL script file opened in Code Editor and executed."))
  7582. except Exception as e:
  7583. log.debug("App.on_filerunscript() -> %s" % str(e))
  7584. sys.exit(2)
  7585. def on_file_saveproject(self, silent=False):
  7586. """
  7587. Callback for menu item File->Save Project. Saves the project to
  7588. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  7589. if set to None. The project is saved by calling ``self.save_project()``.
  7590. :param silent: if True will not display status messages
  7591. :return: None
  7592. """
  7593. self.report_usage("on_file_saveproject")
  7594. if self.project_filename is None:
  7595. self.on_file_saveprojectas()
  7596. else:
  7597. self.worker_task.emit({'fcn': self.save_project,
  7598. 'params': [self.project_filename, silent]})
  7599. if self.defaults["global_open_style"] is False:
  7600. self.file_opened.emit("project", self.project_filename)
  7601. self.file_saved.emit("project", self.project_filename)
  7602. self.set_ui_title(name=self.project_filename)
  7603. self.should_we_save = False
  7604. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7605. """
  7606. Callback for menu item File->Save Project As... Opens a file
  7607. chooser and saves the project to the given file via
  7608. ``self.save_project()``.
  7609. :param make_copy if to be create a copy of the project; boolean
  7610. :param use_thread: if to be run in a separate thread; boolean
  7611. :param quit_action: if to be followed by quiting the application; boolean
  7612. :return: None
  7613. """
  7614. self.report_usage("on_file_saveprojectas")
  7615. self.date = str(datetime.today()).rpartition('.')[0]
  7616. self.date = ''.join(c for c in self.date if c not in ':-')
  7617. self.date = self.date.replace(' ', '_')
  7618. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  7619. try:
  7620. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  7621. caption=_("Save Project As ..."),
  7622. directory=_('{l_save}/Project_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date),
  7623. filter=filter_)
  7624. except TypeError:
  7625. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  7626. filename = str(filename)
  7627. if filename == '':
  7628. self.inform.emit('[WARNING_NOTCL] %s' %
  7629. _("Save Project cancelled."))
  7630. return
  7631. try:
  7632. f = open(filename, 'r')
  7633. f.close()
  7634. except IOError:
  7635. pass
  7636. if use_thread is True:
  7637. self.worker_task.emit({'fcn': self.save_project,
  7638. 'params': [filename, quit_action]})
  7639. else:
  7640. self.save_project(filename, quit_action)
  7641. # self.save_project(filename)
  7642. if self.defaults["global_open_style"] is False:
  7643. self.file_opened.emit("project", filename)
  7644. self.file_saved.emit("project", filename)
  7645. if not make_copy:
  7646. self.project_filename = filename
  7647. self.set_ui_title(name=self.project_filename)
  7648. self.should_we_save = False
  7649. def export_svg(self, obj_name, filename, scale_factor=0.00):
  7650. """
  7651. Exports a Geometry Object to an SVG file.
  7652. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7653. :param filename: Path to the SVG file to save to.
  7654. :param scale_factor: factor by which to change/scale the thickness of the features
  7655. :return:
  7656. """
  7657. self.report_usage("export_svg()")
  7658. if filename is None:
  7659. filename = self.defaults["global_last_save_folder"]
  7660. self.log.debug("export_svg()")
  7661. try:
  7662. obj = self.collection.get_by_name(str(obj_name))
  7663. except:
  7664. # TODO: The return behavior has not been established... should raise exception?
  7665. return "Could not retrieve object: %s" % obj_name
  7666. with self.proc_container.new(_("Exporting SVG")) as proc:
  7667. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7668. # Determine bounding area for svg export
  7669. bounds = obj.bounds()
  7670. size = obj.size()
  7671. # Convert everything to strings for use in the xml doc
  7672. svgwidth = str(size[0])
  7673. svgheight = str(size[1])
  7674. minx = str(bounds[0])
  7675. miny = str(bounds[1] - size[1])
  7676. uom = obj.units.lower()
  7677. # Add a SVG Header and footer to the svg output from shapely
  7678. # The transform flips the Y Axis so that everything renders
  7679. # properly within svg apps such as inkscape
  7680. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7681. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7682. svg_header += 'width="' + svgwidth + uom + '" '
  7683. svg_header += 'height="' + svgheight + uom + '" '
  7684. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7685. svg_header += '<g transform="scale(1,-1)">'
  7686. svg_footer = '</g> </svg>'
  7687. svg_elem = svg_header + exported_svg + svg_footer
  7688. # Parse the xml through a xml parser just to add line feeds
  7689. # and to make it look more pretty for the output
  7690. svgcode = parse_xml_string(svg_elem)
  7691. try:
  7692. with open(filename, 'w') as fp:
  7693. fp.write(svgcode.toprettyxml())
  7694. except PermissionError:
  7695. self.inform.emit('[WARNING] %s' %
  7696. _("Permission denied, saving not possible.\n"
  7697. "Most likely another app is holding the file open and not accessible."))
  7698. return 'fail'
  7699. if self.defaults["global_open_style"] is False:
  7700. self.file_opened.emit("SVG", filename)
  7701. self.file_saved.emit("SVG", filename)
  7702. self.inform.emit('[success] %s: %s' %
  7703. (_("SVG file exported to"), filename))
  7704. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  7705. """
  7706. Exports a Geometry Object to an SVG file in negative.
  7707. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7708. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7709. :param filename: Path to the SVG file to save to.
  7710. :param boundary: thickness of a black border to surround all the features
  7711. :param scale_factor: factor by which to change/scale the thickness of the features
  7712. :param use_thread: if to be run in a separate thread; boolean
  7713. :return:
  7714. """
  7715. self.report_usage("export_negative()")
  7716. if filename is None:
  7717. filename = self.defaults["global_last_save_folder"]
  7718. self.log.debug("export_svg() negative")
  7719. try:
  7720. obj = self.collection.get_by_name(str(obj_name))
  7721. except:
  7722. # TODO: The return behavior has not been established... should raise exception?
  7723. return "Could not retrieve object: %s" % obj_name
  7724. try:
  7725. box = self.collection.get_by_name(str(box_name))
  7726. except:
  7727. # TODO: The return behavior has not been established... should raise exception?
  7728. return "Could not retrieve object: %s" % box_name
  7729. if box is None:
  7730. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7731. (_("No object Box. Using instead"), obj))
  7732. box = obj
  7733. def make_negative_film():
  7734. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7735. # Determine bounding area for svg export
  7736. bounds = box.bounds()
  7737. size = box.size()
  7738. uom = obj.units.lower()
  7739. # Convert everything to strings for use in the xml doc
  7740. svgwidth = str(size[0] + (2 * boundary))
  7741. svgheight = str(size[1] + (2 * boundary))
  7742. minx = str(bounds[0] - boundary)
  7743. miny = str(bounds[1] + boundary + size[1])
  7744. miny_rect = str(bounds[1] - boundary)
  7745. # Add a SVG Header and footer to the svg output from shapely
  7746. # The transform flips the Y Axis so that everything renders
  7747. # properly within svg apps such as inkscape
  7748. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7749. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7750. svg_header += 'width="' + svgwidth + uom + '" '
  7751. svg_header += 'height="' + svgheight + uom + '" '
  7752. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7753. svg_header += '>'
  7754. svg_header += '<g transform="scale(1,-1)">'
  7755. svg_footer = '</g> </svg>'
  7756. # Change the attributes of the exported SVG
  7757. # We don't need stroke-width - wrong, we do when we have lines with certain width
  7758. # We set opacity to maximum
  7759. # We set the color to WHITE
  7760. root = ET.fromstring(exported_svg)
  7761. for child in root:
  7762. child.set('fill', '#FFFFFF')
  7763. child.set('opacity', '1.0')
  7764. child.set('stroke', '#FFFFFF')
  7765. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  7766. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  7767. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  7768. first_svg_elem_tag = 'rect'
  7769. first_svg_elem_attribs = {
  7770. 'x': minx,
  7771. 'y': miny_rect,
  7772. 'width': svgwidth,
  7773. 'height': svgheight,
  7774. 'id': 'neg_rect',
  7775. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  7776. }
  7777. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  7778. exported_svg = ET.tostring(root)
  7779. svg_elem = svg_header + str(exported_svg) + svg_footer
  7780. # Parse the xml through a xml parser just to add line feeds
  7781. # and to make it look more pretty for the output
  7782. doc = parse_xml_string(svg_elem)
  7783. try:
  7784. with open(filename, 'w') as fp:
  7785. fp.write(doc.toprettyxml())
  7786. except PermissionError:
  7787. self.inform.emit('[WARNING] %s' %
  7788. _("Permission denied, saving not possible.\n"
  7789. "Most likely another app is holding the file open and not accessible."))
  7790. return 'fail'
  7791. if self.defaults["global_open_style"] is False:
  7792. self.file_opened.emit("SVG", filename)
  7793. self.file_saved.emit("SVG", filename)
  7794. self.inform.emit('[success] %s: %s' %
  7795. (_("SVG file exported to"), filename))
  7796. if use_thread is True:
  7797. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7798. def job_thread_film(app_obj):
  7799. try:
  7800. make_negative_film()
  7801. except Exception as e:
  7802. proc.done()
  7803. return
  7804. proc.done()
  7805. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7806. else:
  7807. make_negative_film()
  7808. def export_svg_positive(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  7809. """
  7810. Exports a Geometry Object to an SVG file in positive black.
  7811. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7812. :param box_name: the name of the FlatCAM object to be used as delimitation of the content to be saved
  7813. :param filename: Path to the SVG file to save to.
  7814. :param scale_factor: factor by which to change/scale the thickness of the features
  7815. :param use_thread: if to be run in a separate thread; boolean
  7816. :return:
  7817. """
  7818. self.report_usage("export_svg_positive()")
  7819. if filename is None:
  7820. filename = self.defaults["global_last_save_folder"]
  7821. self.log.debug("export_svg() black")
  7822. try:
  7823. obj = self.collection.get_by_name(str(obj_name))
  7824. except:
  7825. # TODO: The return behavior has not been established... should raise exception?
  7826. return "Could not retrieve object: %s" % obj_name
  7827. try:
  7828. box = self.collection.get_by_name(str(box_name))
  7829. except:
  7830. # TODO: The return behavior has not been established... should raise exception?
  7831. return "Could not retrieve object: %s" % box_name
  7832. if box is None:
  7833. self.inform.emit('[WARNING_NOTCL] %s: %s' %
  7834. (_("No object Box. Using instead"), obj))
  7835. box = obj
  7836. def make_positive_film():
  7837. exported_svg = obj.export_svg(scale_factor=scale_factor)
  7838. self.progress.emit(40)
  7839. # Change the attributes of the exported SVG
  7840. # We don't need stroke-width
  7841. # We set opacity to maximum
  7842. # We set the colour to WHITE
  7843. root = ET.fromstring(exported_svg)
  7844. for child in root:
  7845. child.set('fill', str(self.defaults['tools_film_color']))
  7846. child.set('opacity', '1.0')
  7847. child.set('stroke', str(self.defaults['tools_film_color']))
  7848. exported_svg = ET.tostring(root)
  7849. # Determine bounding area for svg export
  7850. bounds = box.bounds()
  7851. size = box.size()
  7852. # This contain the measure units
  7853. uom = obj.units.lower()
  7854. # Define a boundary around SVG of about 1.0mm (~39mils)
  7855. if uom in "mm":
  7856. boundary = 1.0
  7857. else:
  7858. boundary = 0.0393701
  7859. self.progress.emit(80)
  7860. # Convert everything to strings for use in the xml doc
  7861. svgwidth = str(size[0] + (2 * boundary))
  7862. svgheight = str(size[1] + (2 * boundary))
  7863. minx = str(bounds[0] - boundary)
  7864. miny = str(bounds[1] + boundary + size[1])
  7865. self.log.debug(minx)
  7866. self.log.debug(miny)
  7867. # Add a SVG Header and footer to the svg output from shapely
  7868. # The transform flips the Y Axis so that everything renders
  7869. # properly within svg apps such as inkscape
  7870. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7871. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7872. svg_header += 'width="' + svgwidth + uom + '" '
  7873. svg_header += 'height="' + svgheight + uom + '" '
  7874. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7875. svg_header += '>'
  7876. svg_header += '<g transform="scale(1,-1)">'
  7877. svg_footer = '</g> </svg>'
  7878. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  7879. self.progress.emit(90)
  7880. # Parse the xml through a xml parser just to add line feeds
  7881. # and to make it look more pretty for the output
  7882. doc = parse_xml_string(svg_elem)
  7883. try:
  7884. with open(filename, 'w') as fp:
  7885. fp.write(doc.toprettyxml())
  7886. except PermissionError:
  7887. self.inform.emit('[WARNING] %s' %
  7888. _("Permission denied, saving not possible.\n"
  7889. "Most likely another app is holding the file open and not accessible."))
  7890. return 'fail'
  7891. self.progress.emit(100)
  7892. if self.defaults["global_open_style"] is False:
  7893. self.file_opened.emit("SVG", filename)
  7894. self.file_saved.emit("SVG", filename)
  7895. self.inform.emit('[success] %s: %s' %
  7896. (_("SVG file exported to"), filename))
  7897. if use_thread is True:
  7898. proc = self.proc_container.new(_("Generating Film ... Please wait."))
  7899. def job_thread_film(app_obj):
  7900. try:
  7901. make_positive_film()
  7902. except Exception as e:
  7903. proc.done()
  7904. return
  7905. proc.done()
  7906. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  7907. else:
  7908. make_positive_film()
  7909. def save_source_file(self, obj_name, filename, use_thread=True):
  7910. """
  7911. Exports a FlatCAM Object to an Gerber/Excellon file.
  7912. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7913. :param filename: Path to the Gerber file to save to.
  7914. :param use_thread: if to be run in a separate thread
  7915. :return:
  7916. """
  7917. self.report_usage("save source file()")
  7918. if filename is None:
  7919. filename = self.defaults["global_last_save_folder"]
  7920. self.log.debug("save source file()")
  7921. obj = self.collection.get_by_name(obj_name)
  7922. file_string = StringIO(obj.source_file)
  7923. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7924. try:
  7925. with open(filename, 'w') as file:
  7926. file.writelines('G04*\n')
  7927. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7928. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7929. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7930. file.writelines('G04 Created on : %s*\n' % time_string)
  7931. for line in file_string:
  7932. file.writelines(line)
  7933. except PermissionError:
  7934. self.inform.emit('[WARNING] %s' %
  7935. _("Permission denied, saving not possible.\n"
  7936. "Most likely another app is holding the file open and not accessible."))
  7937. return 'fail'
  7938. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7939. """
  7940. Exports a Excellon Object to an Excellon file.
  7941. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7942. :param filename: Path to the Excellon file to save to.
  7943. :param use_thread: if to be run in a separate thread
  7944. :return:
  7945. """
  7946. self.report_usage("export_excellon()")
  7947. if filename is None:
  7948. filename = self.defaults["global_last_save_folder"]
  7949. self.log.debug("export_excellon()")
  7950. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7951. self.defaults["excellon_exp_decimals"]
  7952. )
  7953. units = ''
  7954. if local_use is None:
  7955. try:
  7956. obj = self.collection.get_by_name(str(obj_name))
  7957. except:
  7958. # TODO: The return behavior has not been established... should raise exception?
  7959. return "Could not retrieve object: %s" % obj_name
  7960. else:
  7961. obj = local_use
  7962. # updated units
  7963. eunits = self.defaults["excellon_exp_units"]
  7964. ewhole = self.defaults["excellon_exp_integer"]
  7965. efract = self.defaults["excellon_exp_decimals"]
  7966. ezeros = self.defaults["excellon_exp_zeros"]
  7967. eformat = self.defaults["excellon_exp_format"]
  7968. slot_type = self.defaults["excellon_exp_slot_type"]
  7969. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  7970. if fc_units == 'MM':
  7971. factor = 1 if eunits == 'METRIC' else 0.03937
  7972. else:
  7973. factor = 25.4 if eunits == 'METRIC' else 1
  7974. def make_excellon():
  7975. try:
  7976. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7977. header = 'M48\n'
  7978. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7979. (str(self.version), str(self.version_date))
  7980. header += ';Filename: %s' % str(obj_name) + '\n'
  7981. header += ';Created on : %s' % time_str + '\n'
  7982. if eformat == 'dec':
  7983. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7984. header += eunits + '\n'
  7985. for tool in obj.tools:
  7986. if eunits == 'METRIC':
  7987. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7988. tool=str(tool),
  7989. dec=2)
  7990. else:
  7991. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7992. tool=str(tool),
  7993. dec=4)
  7994. else:
  7995. if ezeros == 'LZ':
  7996. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7997. form='ndec', e_zeros='LZ', factor=factor,
  7998. slot_type=slot_type)
  7999. header += '%s,%s\n' % (eunits, 'LZ')
  8000. header += format_exc
  8001. for tool in obj.tools:
  8002. if eunits == 'METRIC':
  8003. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8004. tool=str(tool),
  8005. dec=2)
  8006. else:
  8007. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8008. tool=str(tool),
  8009. dec=4)
  8010. else:
  8011. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  8012. form='ndec', e_zeros='TZ', factor=factor,
  8013. slot_type=slot_type)
  8014. header += '%s,%s\n' % (eunits, 'TZ')
  8015. header += format_exc
  8016. for tool in obj.tools:
  8017. if eunits == 'METRIC':
  8018. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8019. tool=str(tool),
  8020. dec=2)
  8021. else:
  8022. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  8023. tool=str(tool),
  8024. dec=4)
  8025. header += '%\n'
  8026. footer = 'M30\n'
  8027. exported_excellon = header
  8028. exported_excellon += excellon_code
  8029. exported_excellon += footer
  8030. if local_use is None:
  8031. try:
  8032. with open(filename, 'w') as fp:
  8033. fp.write(exported_excellon)
  8034. except PermissionError:
  8035. self.inform.emit('[WARNING] %s' %
  8036. _("Permission denied, saving not possible.\n"
  8037. "Most likely another app is holding the file open and not accessible."))
  8038. return 'fail'
  8039. if self.defaults["global_open_style"] is False:
  8040. self.file_opened.emit("Excellon", filename)
  8041. self.file_saved.emit("Excellon", filename)
  8042. self.inform.emit('[success] %s: %s' %
  8043. (_("Excellon file exported to"), filename))
  8044. else:
  8045. return exported_excellon
  8046. except Exception as e:
  8047. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  8048. return 'fail'
  8049. if use_thread is True:
  8050. with self.proc_container.new(_("Exporting Excellon")) as proc:
  8051. def job_thread_exc(app_obj):
  8052. ret = make_excellon()
  8053. if ret == 'fail':
  8054. self.inform.emit('[ERROR_NOTCL] %s' %
  8055. _('Could not export Excellon file.'))
  8056. return
  8057. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8058. else:
  8059. ret = make_excellon()
  8060. if ret == 'fail':
  8061. self.inform.emit('[ERROR_NOTCL] %s' %
  8062. _('Could not export Excellon file.'))
  8063. return 'fail'
  8064. if local_use is not None:
  8065. return ret
  8066. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  8067. """
  8068. Exports a Gerber Object to an Gerber file.
  8069. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  8070. :param filename: Path to the Gerber file to save to.
  8071. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  8072. When not None, the value will be the actual Gerber object for which to create the Gerber code
  8073. :param use_thread: if to be run in a separate thread
  8074. :return:
  8075. """
  8076. self.report_usage("export_gerber()")
  8077. if filename is None:
  8078. filename = self.defaults["global_last_save_folder"]
  8079. self.log.debug("export_gerber()")
  8080. if local_use is None:
  8081. try:
  8082. obj = self.collection.get_by_name(str(obj_name))
  8083. except:
  8084. # TODO: The return behavior has not been established... should raise exception?
  8085. return "Could not retrieve object: %s" % obj_name
  8086. else:
  8087. obj = local_use
  8088. # updated units
  8089. gunits = self.defaults["gerber_exp_units"]
  8090. gwhole = self.defaults["gerber_exp_integer"]
  8091. gfract = self.defaults["gerber_exp_decimals"]
  8092. gzeros = self.defaults["gerber_exp_zeros"]
  8093. fc_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8094. if fc_units == 'MM':
  8095. factor = 1 if gunits == 'MM' else 0.03937
  8096. else:
  8097. factor = 25.4 if gunits == 'MM' else 1
  8098. def make_gerber():
  8099. try:
  8100. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8101. header = 'G04*\n'
  8102. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  8103. (str(self.version), str(self.version_date))
  8104. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  8105. header += 'G04 Created on : %s*' % time_str + '\n'
  8106. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  8107. header += "%MO{units}*%\n".format(units=gunits)
  8108. for apid in obj.apertures:
  8109. if obj.apertures[apid]['type'] == 'C':
  8110. header += "%ADD{apid}{type},{size}*%\n".format(
  8111. apid=str(apid),
  8112. type='C',
  8113. size=(factor * obj.apertures[apid]['size'])
  8114. )
  8115. elif obj.apertures[apid]['type'] == 'R':
  8116. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8117. apid=str(apid),
  8118. type='R',
  8119. width=(factor * obj.apertures[apid]['width']),
  8120. height=(factor * obj.apertures[apid]['height'])
  8121. )
  8122. elif obj.apertures[apid]['type'] == 'O':
  8123. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  8124. apid=str(apid),
  8125. type='O',
  8126. width=(factor * obj.apertures[apid]['width']),
  8127. height=(factor * obj.apertures[apid]['height'])
  8128. )
  8129. header += '\n'
  8130. # obsolete units but some software may need it
  8131. if gunits == 'IN':
  8132. header += 'G70*\n'
  8133. else:
  8134. header += 'G71*\n'
  8135. # Absolute Mode
  8136. header += 'G90*\n'
  8137. header += 'G01*\n'
  8138. # positive polarity
  8139. header += '%LPD*%\n'
  8140. footer = 'M02*\n'
  8141. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  8142. exported_gerber = header
  8143. exported_gerber += gerber_code
  8144. exported_gerber += footer
  8145. if local_use is None:
  8146. try:
  8147. with open(filename, 'w') as fp:
  8148. fp.write(exported_gerber)
  8149. except PermissionError:
  8150. self.inform.emit('[WARNING] %s' %
  8151. _("Permission denied, saving not possible.\n"
  8152. "Most likely another app is holding the file open and not accessible."))
  8153. return 'fail'
  8154. if self.defaults["global_open_style"] is False:
  8155. self.file_opened.emit("Gerber", filename)
  8156. self.file_saved.emit("Gerber", filename)
  8157. self.inform.emit('[success] %s: %s' %
  8158. (_("Gerber file exported to"), filename))
  8159. else:
  8160. return exported_gerber
  8161. except Exception as e:
  8162. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  8163. return 'fail'
  8164. if use_thread is True:
  8165. with self.proc_container.new(_("Exporting Gerber")) as proc:
  8166. def job_thread_grb(app_obj):
  8167. ret = make_gerber()
  8168. if ret == 'fail':
  8169. self.inform.emit('[ERROR_NOTCL] %s' %
  8170. _('Could not export Gerber file.'))
  8171. return
  8172. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  8173. else:
  8174. ret = make_gerber()
  8175. if ret == 'fail':
  8176. self.inform.emit('[ERROR_NOTCL] %s' %
  8177. _('Could not export Gerber file.'))
  8178. return 'fail'
  8179. if local_use is not None:
  8180. return ret
  8181. def export_dxf(self, obj_name, filename, use_thread=True):
  8182. """
  8183. Exports a Geometry Object to an DXF file.
  8184. :param obj_name: the name of the FlatCAM object to be saved as DXF
  8185. :param filename: Path to the DXF file to save to.
  8186. :param use_thread: if to be run in a separate thread
  8187. :return:
  8188. """
  8189. self.report_usage("export_dxf()")
  8190. if filename is None:
  8191. filename = self.defaults["global_last_save_folder"]
  8192. self.log.debug("export_dxf()")
  8193. format_exc = ''
  8194. units = ''
  8195. try:
  8196. obj = self.collection.get_by_name(str(obj_name))
  8197. except:
  8198. # TODO: The return behavior has not been established... should raise exception?
  8199. return "Could not retrieve object: %s" % obj_name
  8200. # updated units
  8201. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8202. if units == 'IN' or units == 'INCH':
  8203. units = 'INCH'
  8204. elif units == 'MM' or units == 'METIRC':
  8205. units ='METRIC'
  8206. def make_dxf():
  8207. try:
  8208. dxf_code = obj.export_dxf()
  8209. dxf_code.saveas(filename)
  8210. if self.defaults["global_open_style"] is False:
  8211. self.file_opened.emit("DXF", filename)
  8212. self.file_saved.emit("DXF", filename)
  8213. self.inform.emit('[success] %s: %s' %
  8214. (_("DXF file exported to"), filename))
  8215. except:
  8216. return 'fail'
  8217. if use_thread is True:
  8218. with self.proc_container.new(_("Exporting DXF")) as proc:
  8219. def job_thread_exc(app_obj):
  8220. ret = make_dxf()
  8221. if ret == 'fail':
  8222. app_obj.inform.emit('[WARNING_NOTCL] %s' %
  8223. _('Could not export DXF file.'))
  8224. return
  8225. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  8226. else:
  8227. ret = make_dxf()
  8228. if ret == 'fail':
  8229. self.inform.emit('[WARNING_NOTCL] %s' %
  8230. _('Could not export DXF file.'))
  8231. return
  8232. def import_svg(self, filename, geo_type='geometry', outname=None):
  8233. """
  8234. Adds a new Geometry Object to the projects and populates
  8235. it with shapes extracted from the SVG file.
  8236. :param filename: Path to the SVG file.
  8237. :param outname:
  8238. :return:
  8239. """
  8240. self.report_usage("import_svg()")
  8241. obj_type = ""
  8242. if geo_type is None or geo_type == "geometry":
  8243. obj_type = "geometry"
  8244. elif geo_type == "gerber":
  8245. obj_type = geo_type
  8246. else:
  8247. self.inform.emit('[ERROR_NOTCL] %s' %
  8248. _("Not supported type is picked as parameter. "
  8249. "Only Geometry and Gerber are supported"))
  8250. return
  8251. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8252. def obj_init(geo_obj, app_obj):
  8253. geo_obj.import_svg(filename, obj_type, units=units)
  8254. geo_obj.multigeo = False
  8255. with self.proc_container.new(_("Importing SVG")) as proc:
  8256. # Object name
  8257. name = outname or filename.split('/')[-1].split('\\')[-1]
  8258. self.new_object(obj_type, name, obj_init, autoselected=False)
  8259. self.progress.emit(20)
  8260. # Register recent file
  8261. self.file_opened.emit("svg", filename)
  8262. # GUI feedback
  8263. self.inform.emit('[success] %s: %s' %
  8264. (_("Opened"), filename))
  8265. self.progress.emit(100)
  8266. def import_dxf(self, filename, geo_type='geometry', outname=None):
  8267. """
  8268. Adds a new Geometry Object to the projects and populates
  8269. it with shapes extracted from the DXF file.
  8270. :param filename: Path to the DXF file.
  8271. :param outname:
  8272. :type putname: str
  8273. :return:
  8274. """
  8275. self.report_usage("import_dxf()")
  8276. obj_type = ""
  8277. if geo_type is None or geo_type == "geometry":
  8278. obj_type = "geometry"
  8279. elif geo_type == "gerber":
  8280. obj_type = geo_type
  8281. else:
  8282. self.inform.emit('[ERROR_NOTCL] %s' %
  8283. _("Not supported type is picked as parameter. "
  8284. "Only Geometry and Gerber are supported"))
  8285. return
  8286. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  8287. def obj_init(geo_obj, app_obj):
  8288. geo_obj.import_dxf(filename, obj_type, units=units)
  8289. geo_obj.multigeo = False
  8290. with self.proc_container.new(_("Importing DXF")) as proc:
  8291. # Object name
  8292. name = outname or filename.split('/')[-1].split('\\')[-1]
  8293. self.new_object(obj_type, name, obj_init, autoselected=False)
  8294. self.progress.emit(20)
  8295. # Register recent file
  8296. self.file_opened.emit("dxf", filename)
  8297. # GUI feedback
  8298. self.inform.emit('[success] %s: %s' %
  8299. (_("Opened"), filename))
  8300. self.progress.emit(100)
  8301. def import_image(self, filename, o_type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  8302. """
  8303. Adds a new Geometry Object to the projects and populates
  8304. it with shapes extracted from the SVG file.
  8305. :param filename: Path to the SVG file.
  8306. :param o_type: type of FlatCAM objeect
  8307. :param dpi: dot per inch
  8308. :param mode: black or color
  8309. :param mask: dictate the level of detail
  8310. :param outname: name for the resulting file
  8311. :return:
  8312. """
  8313. self.report_usage("import_image()")
  8314. if o_type is None or o_type == "geometry":
  8315. obj_type = "geometry"
  8316. elif o_type == "gerber":
  8317. obj_type = o_type
  8318. else:
  8319. self.inform.emit('[ERROR_NOTCL] %s' %
  8320. _("Not supported type is picked as parameter. "
  8321. "Only Geometry and Gerber are supported"))
  8322. return
  8323. def obj_init(geo_obj, app_obj):
  8324. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  8325. geo_obj.multigeo = False
  8326. with self.proc_container.new(_("Importing Image")) as proc:
  8327. # Object name
  8328. name = outname or filename.split('/')[-1].split('\\')[-1]
  8329. units = self.ui.general_defaults_form.general_app_group.units_radio.get_value()
  8330. self.new_object(obj_type, name, obj_init)
  8331. self.progress.emit(20)
  8332. # Register recent file
  8333. self.file_opened.emit("image", filename)
  8334. # GUI feedback
  8335. self.inform.emit('[success] %s: %s' %
  8336. (_("Opened"), filename))
  8337. self.progress.emit(100)
  8338. def open_gerber(self, filename, outname=None):
  8339. """
  8340. Opens a Gerber file, parses it and creates a new object for
  8341. it in the program. Thread-safe.
  8342. :param outname: Name of the resulting object. None causes the
  8343. name to be that of the file.
  8344. :param filename: Gerber file filename
  8345. :type filename: str
  8346. :param follow: If true, the parser will not create polygons, just lines
  8347. following the gerber path.
  8348. :type follow: bool
  8349. :return: None
  8350. """
  8351. # How the object should be initialized
  8352. def obj_init(gerber_obj, app_obj):
  8353. assert isinstance(gerber_obj, FlatCAMGerber), \
  8354. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  8355. # Opening the file happens here
  8356. self.progress.emit(30)
  8357. try:
  8358. gerber_obj.parse_file(filename)
  8359. except IOError:
  8360. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8361. (_("Failed to open file"), filename))
  8362. app_obj.progress.emit(0)
  8363. return "fail"
  8364. except ParseError as err:
  8365. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' %
  8366. (_("Failed to parse file"), filename, str(err)))
  8367. app_obj.progress.emit(0)
  8368. self.log.error(str(err))
  8369. return "fail"
  8370. except Exception as e:
  8371. log.debug("App.open_gerber() --> %s" % str(e))
  8372. msg = '[ERROR] %s' % \
  8373. _("An internal error has occurred. See shell.\n")
  8374. msg += traceback.format_exc()
  8375. app_obj.inform.emit(msg)
  8376. return "fail"
  8377. if gerber_obj.is_empty():
  8378. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  8379. # self.collection.set_active(gerber_obj.options["name"])
  8380. # self.collection.delete_active()
  8381. self.inform.emit('[ERROR_NOTCL] %s' %
  8382. _("Object is not Gerber file or empty. Aborting object creation."))
  8383. return "fail"
  8384. # Further parsing
  8385. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  8386. App.log.debug("open_gerber()")
  8387. with self.proc_container.new(_("Opening Gerber")) as proc:
  8388. self.progress.emit(10)
  8389. # Object name
  8390. name = outname or filename.split('/')[-1].split('\\')[-1]
  8391. # # ## Object creation # ##
  8392. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  8393. if ret == 'fail':
  8394. self.inform.emit('[ERROR_NOTCL]%s' %
  8395. _(' Open Gerber failed. Probable not a Gerber file.'))
  8396. return
  8397. # Register recent file
  8398. self.file_opened.emit("gerber", filename)
  8399. self.progress.emit(100)
  8400. # GUI feedback
  8401. self.inform.emit('[success] %s: %s' %
  8402. (_("Opened"), filename))
  8403. def open_excellon(self, filename, outname=None, plot=True):
  8404. """
  8405. Opens an Excellon file, parses it and creates a new object for
  8406. it in the program. Thread-safe.
  8407. :param outname: Name of the resulting object. None causes the
  8408. name to be that of the file.
  8409. :param filename: Excellon file filename
  8410. :type filename: str
  8411. :return: None
  8412. """
  8413. App.log.debug("open_excellon()")
  8414. # How the object should be initialized
  8415. def obj_init(excellon_obj, app_obj):
  8416. # self.progress.emit(20)
  8417. try:
  8418. ret = excellon_obj.parse_file(filename=filename)
  8419. if ret == "fail":
  8420. log.debug("Excellon parsing failed.")
  8421. self.inform.emit('[ERROR_NOTCL] %s' %
  8422. _("This is not Excellon file."))
  8423. return "fail"
  8424. except IOError:
  8425. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8426. (_("Cannot open file"), filename))
  8427. log.debug("Could not open Excellon object.")
  8428. self.progress.emit(0) # TODO: self and app_bjj mixed
  8429. return "fail"
  8430. except:
  8431. msg = '[ERROR_NOTCL] %s' % \
  8432. _("An internal error has occurred. See shell.\n")
  8433. msg += traceback.format_exc()
  8434. app_obj.inform.emit(msg)
  8435. return "fail"
  8436. ret = excellon_obj.create_geometry()
  8437. if ret == 'fail':
  8438. log.debug("Could not create geometry for Excellon object.")
  8439. return "fail"
  8440. for tool in excellon_obj.tools:
  8441. if excellon_obj.tools[tool]['solid_geometry']:
  8442. return
  8443. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  8444. (_("No geometry found in file"), filename))
  8445. return "fail"
  8446. with self.proc_container.new(_("Opening Excellon.")):
  8447. # Object name
  8448. name = outname or filename.split('/')[-1].split('\\')[-1]
  8449. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  8450. if ret_val == 'fail':
  8451. self.inform.emit('[ERROR_NOTCL] %s' %
  8452. _('Open Excellon file failed. Probable not an Excellon file.'))
  8453. return
  8454. # Register recent file
  8455. self.file_opened.emit("excellon", filename)
  8456. # GUI feedback
  8457. self.inform.emit('[success] %s: %s' %
  8458. (_("Opened"), filename))
  8459. def open_gcode(self, filename, outname=None, plot=True):
  8460. """
  8461. Opens a G-gcode file, parses it and creates a new object for
  8462. it in the program. Thread-safe.
  8463. :param outname: Name of the resulting object. None causes the name to be that of the file.
  8464. :param filename: G-code file filename
  8465. :type filename: str
  8466. :return: None
  8467. """
  8468. App.log.debug("open_gcode()")
  8469. # How the object should be initialized
  8470. def obj_init(job_obj, app_obj_):
  8471. """
  8472. :param job_obj: the resulting object
  8473. :type app_obj_: App
  8474. """
  8475. assert isinstance(app_obj_, App), \
  8476. "Initializer expected App, got %s" % type(app_obj_)
  8477. self.progress.emit(10)
  8478. try:
  8479. f = open(filename)
  8480. gcode = f.read()
  8481. f.close()
  8482. except IOError:
  8483. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  8484. (_("Failed to open"), filename))
  8485. self.progress.emit(0)
  8486. return "fail"
  8487. job_obj.gcode = gcode
  8488. self.progress.emit(20)
  8489. ret = job_obj.gcode_parse()
  8490. if ret == "fail":
  8491. self.inform.emit('[ERROR_NOTCL] %s' %
  8492. _("This is not GCODE"))
  8493. return "fail"
  8494. self.progress.emit(60)
  8495. job_obj.create_geometry()
  8496. with self.proc_container.new(_("Opening G-Code.")):
  8497. # Object name
  8498. name = outname or filename.split('/')[-1].split('\\')[-1]
  8499. # New object creation and file processing
  8500. ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  8501. if ret == 'fail':
  8502. self.inform.emit('[ERROR_NOTCL] %s' %
  8503. _("Failed to create CNCJob Object. Probable not a GCode file.\n "
  8504. "Attempting to create a FlatCAM CNCJob Object from "
  8505. "G-Code file failed during processing"))
  8506. return "fail"
  8507. # Register recent file
  8508. self.file_opened.emit("cncjob", filename)
  8509. # GUI feedback
  8510. self.inform.emit('[success] %s: %s' %
  8511. (_("Opened"), filename))
  8512. self.progress.emit(100)
  8513. def open_config_file(self, filename, run_from_arg=None):
  8514. """
  8515. Loads a config file from the specified file.
  8516. :param filename: Name of the file from which to load.
  8517. :type filename: str
  8518. :return: None
  8519. """
  8520. App.log.debug("Opening config file: " + filename)
  8521. if run_from_arg:
  8522. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8523. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8524. _("Opening FlatCAM Config file.")),
  8525. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8526. color=QtGui.QColor("gray"))
  8527. # add the tab if it was closed
  8528. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, _("Code Editor"))
  8529. # first clear previous text in text editor (if any)
  8530. self.ui.code_editor.clear()
  8531. # Switch plot_area to CNCJob tab
  8532. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  8533. try:
  8534. if filename:
  8535. f = QtCore.QFile(filename)
  8536. if f.open(QtCore.QIODevice.ReadOnly):
  8537. stream = QtCore.QTextStream(f)
  8538. gcode_edited = stream.readAll()
  8539. self.ui.code_editor.setPlainText(gcode_edited)
  8540. f.close()
  8541. except IOError:
  8542. App.log.error("Failed to open config file: %s" % filename)
  8543. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8544. (_("Failed to open config file"), filename))
  8545. return
  8546. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  8547. """
  8548. Loads a project from the specified file.
  8549. 1) Loads and parses file
  8550. 2) Registers the file as recently opened.
  8551. 3) Calls on_file_new()
  8552. 4) Updates options
  8553. 5) Calls new_object() with the object's from_dict() as init method.
  8554. 6) Calls plot_all() if plot=True
  8555. :param filename: Name of the file from which to load.
  8556. :type filename: str
  8557. :param run_from_arg: True if run for arguments
  8558. :param plot: If True plot all objects in the project
  8559. :param cli: run from command line
  8560. :return: None
  8561. """
  8562. App.log.debug("Opening project: " + filename)
  8563. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8564. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8565. if cli is None:
  8566. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  8567. if run_from_arg:
  8568. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  8569. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8570. _("Opening FlatCAM Project file.")),
  8571. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8572. color=QtGui.QColor("gray"))
  8573. # Open and parse an uncompressed Project file
  8574. try:
  8575. f = open(filename, 'r')
  8576. except IOError:
  8577. App.log.error("Failed to open project file: %s" % filename)
  8578. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8579. (_("Failed to open project file"), filename))
  8580. return
  8581. try:
  8582. d = json.load(f, object_hook=dict2obj)
  8583. except Exception as e:
  8584. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  8585. (filename, str(e)))
  8586. f.close()
  8587. # Open and parse a compressed Project file
  8588. try:
  8589. with lzma.open(filename) as f:
  8590. file_content = f.read().decode('utf-8')
  8591. d = json.loads(file_content, object_hook=dict2obj)
  8592. except Exception as e:
  8593. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  8594. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  8595. (_("Failed to open project file"), filename))
  8596. return
  8597. # Clear the current project
  8598. # # NOT THREAD SAFE # ##
  8599. if run_from_arg is True:
  8600. pass
  8601. elif cli is True:
  8602. self.delete_selection_shape()
  8603. else:
  8604. self.on_file_new()
  8605. # Project options
  8606. self.options.update(d['options'])
  8607. self.project_filename = filename
  8608. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8609. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8610. if cli is None:
  8611. self.set_screen_units(self.options["units"])
  8612. # Re create objects
  8613. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8614. for obj in d['objs']:
  8615. def obj_init(obj_inst, app_inst):
  8616. obj_inst.from_dict(obj)
  8617. App.log.debug("Recreating from opened project an %s object: %s" %
  8618. (obj['kind'].capitalize(), obj['options']['name']))
  8619. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8620. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8621. if cli is None:
  8622. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8623. obj['kind'].upper(),
  8624. obj['options']['name']
  8625. )
  8626. )
  8627. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8628. self.inform.emit('[success] %s: %s' %
  8629. (_("Project loaded from"), filename))
  8630. self.should_we_save = False
  8631. self.file_opened.emit("project", filename)
  8632. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8633. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8634. if cli is None:
  8635. self.set_ui_title(name=self.project_filename)
  8636. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8637. def propagate_defaults(self, silent=False):
  8638. """
  8639. This method is used to set default values in classes. It's
  8640. an alternative to project options but allows the use
  8641. of values invisible to the user.
  8642. :return: None
  8643. """
  8644. if silent is False:
  8645. self.log.debug("propagate_defaults()")
  8646. # Which objects to update the given parameters.
  8647. routes = {
  8648. "global_zdownrate": CNCjob,
  8649. "excellon_zeros": Excellon,
  8650. "excellon_format_upper_in": Excellon,
  8651. "excellon_format_lower_in": Excellon,
  8652. "excellon_format_upper_mm": Excellon,
  8653. "excellon_format_lower_mm": Excellon,
  8654. "excellon_units": Excellon,
  8655. "gerber_use_buffer_for_union": Gerber,
  8656. "geometry_multidepth": Geometry
  8657. }
  8658. for param in routes:
  8659. if param in routes[param].defaults:
  8660. try:
  8661. routes[param].defaults[param] = self.defaults[param]
  8662. if silent is False:
  8663. self.log.debug(" " + param + " OK")
  8664. except KeyError:
  8665. if silent is False:
  8666. self.log.debug(" ERROR: " + param + " not in defaults.")
  8667. else:
  8668. # Try extracting the name:
  8669. # classname_param here is param in the object
  8670. if param.find(routes[param].__name__.lower() + "_") == 0:
  8671. p = param[len(routes[param].__name__) + 1:]
  8672. if p in routes[param].defaults:
  8673. routes[param].defaults[p] = self.defaults[param]
  8674. if silent is False:
  8675. self.log.debug(" " + param + " OK!")
  8676. def restore_main_win_geom(self):
  8677. try:
  8678. self.ui.setGeometry(self.defaults["global_def_win_x"],
  8679. self.defaults["global_def_win_y"],
  8680. self.defaults["global_def_win_w"],
  8681. self.defaults["global_def_win_h"])
  8682. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  8683. except KeyError as e:
  8684. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  8685. def plot_all(self, zoom=True):
  8686. """
  8687. Re-generates all plots from all objects.
  8688. :return: None
  8689. """
  8690. self.log.debug("Plot_all()")
  8691. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8692. for obj in self.collection.get_list():
  8693. def worker_task(obj):
  8694. with self.proc_container.new("Plotting"):
  8695. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8696. if zoom:
  8697. self.object_plotted.emit(obj)
  8698. # Send to worker
  8699. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  8700. def register_folder(self, filename):
  8701. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8702. def register_save_folder(self, filename):
  8703. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8704. def set_progress_bar(self, percentage, text=""):
  8705. self.ui.progress_bar.setValue(int(percentage))
  8706. def setup_shell(self):
  8707. """
  8708. Creates shell functions. Runs once at startup.
  8709. :return: None
  8710. """
  8711. self.log.debug("setup_shell()")
  8712. def shelp(p=None):
  8713. if not p:
  8714. return _("Available commands:\n") + \
  8715. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  8716. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  8717. if p not in commands:
  8718. return "Unknown command: %s" % p
  8719. return commands[p]["help"]
  8720. # --- Migrated to new architecture ---
  8721. # def options(name):
  8722. # ops = self.collection.get_by_name(str(name)).options
  8723. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  8724. def h(*args):
  8725. """
  8726. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  8727. and standalone parameters into list.
  8728. """
  8729. kwa = {}
  8730. a = []
  8731. n = len(args)
  8732. name = None
  8733. for i in range(n):
  8734. match = re.search(r'^-([a-zA-Z].*)', args[i])
  8735. if match:
  8736. assert name is None
  8737. name = match.group(1)
  8738. continue
  8739. if name is None:
  8740. a.append(args[i])
  8741. else:
  8742. kwa[name] = args[i]
  8743. name = None
  8744. return a, kwa
  8745. @contextmanager
  8746. def wait_signal(signal, timeout=10000):
  8747. """
  8748. Block loop until signal emitted, timeout (ms) elapses
  8749. or unhandled exception happens in a thread.
  8750. :param timeout: time after which the loop is exited
  8751. :param signal: Signal to wait for.
  8752. """
  8753. loop = QtCore.QEventLoop()
  8754. # Normal termination
  8755. signal.connect(loop.quit)
  8756. # Termination by exception in thread
  8757. self.thread_exception.connect(loop.quit)
  8758. status = {'timed_out': False}
  8759. def report_quit():
  8760. status['timed_out'] = True
  8761. loop.quit()
  8762. yield
  8763. # Temporarily change how exceptions are managed.
  8764. oeh = sys.excepthook
  8765. ex = []
  8766. def except_hook(type_, value, traceback_):
  8767. ex.append(value)
  8768. oeh(type_, value, traceback_)
  8769. sys.excepthook = except_hook
  8770. # Terminate on timeout
  8771. if timeout is not None:
  8772. QtCore.QTimer.singleShot(timeout, report_quit)
  8773. # # ## Block ## ##
  8774. loop.exec_()
  8775. # Restore exception management
  8776. sys.excepthook = oeh
  8777. if ex:
  8778. self.raiseTclError(str(ex[0]))
  8779. if status['timed_out']:
  8780. raise Exception('Timed out!')
  8781. def make_docs():
  8782. output = ''
  8783. import collections
  8784. od = collections.OrderedDict(sorted(commands.items()))
  8785. for cmd_, val in od.items():
  8786. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  8787. t = val['help']
  8788. usage_i = t.find('>')
  8789. if usage_i < 0:
  8790. expl = t
  8791. output += expl + '\n\n'
  8792. continue
  8793. expl = t[:usage_i - 1]
  8794. output += expl + '\n\n'
  8795. end_usage_i = t[usage_i:].find('\n')
  8796. if end_usage_i < 0:
  8797. end_usage_i = len(t[usage_i:])
  8798. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  8799. else:
  8800. extras = t[usage_i+end_usage_i+1:]
  8801. parts = [s.strip() for s in extras.split('\n')]
  8802. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  8803. for p in parts:
  8804. output += ' ' + p + '\n\n'
  8805. return output
  8806. '''
  8807. Howto implement TCL shell commands:
  8808. All parameters passed to command should be possible to set as None and test it afterwards.
  8809. This is because we need to see error caused in tcl,
  8810. if None value as default parameter is not allowed TCL will return empty error.
  8811. Use:
  8812. def mycommand(name=None,...):
  8813. Test it like this:
  8814. if name is None:
  8815. self.raise_tcl_error('Argument name is missing.')
  8816. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  8817. otherwise we will miss it and processing will silently continue.
  8818. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  8819. which is catched in exec_command and displayed in TCL shell console with red background.
  8820. Error in console is displayed with TCL trace.
  8821. This behavior works only within main thread,
  8822. errors with promissed tasks can be catched and detected only with log.
  8823. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  8824. TCL shell.
  8825. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  8826. '''
  8827. commands = {
  8828. 'help': {
  8829. 'fcn': shelp,
  8830. 'help': _("Shows list of commands.")
  8831. },
  8832. }
  8833. # Import/overwrite tcl commands as objects of TclCommand descendants
  8834. # This modifies the variable 'commands'.
  8835. tclCommands.register_all_commands(self, commands)
  8836. # Add commands to the tcl interpreter
  8837. for cmd in commands:
  8838. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  8839. # Make the tcl puts function return instead of print to stdout
  8840. self.tcl.eval('''
  8841. rename puts original_puts
  8842. proc puts {args} {
  8843. if {[llength $args] == 1} {
  8844. return "[lindex $args 0]"
  8845. } else {
  8846. eval original_puts $args
  8847. }
  8848. }
  8849. ''')
  8850. def setup_recent_items(self):
  8851. # TODO: Move this to constructor
  8852. icons = {
  8853. "gerber": "share/flatcam_icon16.png",
  8854. "excellon": "share/drill16.png",
  8855. 'geometry': "share/geometry16.png",
  8856. "cncjob": "share/cnc16.png",
  8857. "project": "share/project16.png",
  8858. "svg": "share/geometry16.png",
  8859. "dxf": "share/dxf16.png",
  8860. "pdf": "share/pdf32.png",
  8861. "image": "share/image16.png"
  8862. }
  8863. openers = {
  8864. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8865. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8866. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8867. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8868. 'project': self.open_project,
  8869. 'svg': self.import_svg,
  8870. 'dxf': self.import_dxf,
  8871. 'image': self.import_image,
  8872. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8873. }
  8874. # Open recent file for files
  8875. try:
  8876. f = open(self.data_path + '/recent.json')
  8877. except IOError:
  8878. App.log.error("Failed to load recent item list.")
  8879. self.inform.emit('[ERROR_NOTCL] %s' %
  8880. _("Failed to load recent item list."))
  8881. return
  8882. try:
  8883. self.recent = json.load(f)
  8884. except json.scanner.JSONDecodeError:
  8885. App.log.error("Failed to parse recent item list.")
  8886. self.inform.emit('[ERROR_NOTCL] %s' %
  8887. _("Failed to parse recent item list."))
  8888. f.close()
  8889. return
  8890. f.close()
  8891. # Open recent file for projects
  8892. try:
  8893. fp = open(self.data_path + '/recent_projects.json')
  8894. except IOError:
  8895. App.log.error("Failed to load recent project item list.")
  8896. self.inform.emit('[ERROR_NOTCL] %s' %
  8897. _("Failed to load recent projects item list."))
  8898. return
  8899. try:
  8900. self.recent_projects = json.load(fp)
  8901. except json.scanner.JSONDecodeError:
  8902. App.log.error("Failed to parse recent project item list.")
  8903. self.inform.emit('[ERROR_NOTCL] %s' %
  8904. _("Failed to parse recent project item list."))
  8905. fp.close()
  8906. return
  8907. fp.close()
  8908. # Closure needed to create callbacks in a loop.
  8909. # Otherwise late binding occurs.
  8910. def make_callback(func, fname):
  8911. def opener():
  8912. func(fname)
  8913. return opener
  8914. def reset_recent_files():
  8915. # Reset menu
  8916. self.ui.recent.clear()
  8917. self.recent = []
  8918. try:
  8919. f = open(self.data_path + '/recent.json', 'w')
  8920. except IOError:
  8921. App.log.error("Failed to open recent items file for writing.")
  8922. return
  8923. json.dump(self.recent, f)
  8924. def reset_recent_projects():
  8925. # Reset menu
  8926. self.ui.recent_projects.clear()
  8927. self.recent_projects = []
  8928. try:
  8929. fp = open(self.data_path + '/recent_projects.json', 'w')
  8930. except IOError:
  8931. App.log.error("Failed to open recent projects items file for writing.")
  8932. return
  8933. json.dump(self.recent, fp)
  8934. # Reset menu
  8935. self.ui.recent.clear()
  8936. self.ui.recent_projects.clear()
  8937. # Create menu items for projects
  8938. for recent in self.recent_projects:
  8939. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8940. if recent['kind'] == 'project':
  8941. try:
  8942. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8943. # Attach callback
  8944. o = make_callback(openers[recent["kind"]], recent['filename'])
  8945. action.triggered.connect(o)
  8946. self.ui.recent_projects.addAction(action)
  8947. except KeyError:
  8948. App.log.error("Unsupported file type: %s" % recent["kind"])
  8949. # Last action in Recent Files menu is one that Clear the content
  8950. clear_action_proj = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8951. clear_action_proj.triggered.connect(reset_recent_projects)
  8952. self.ui.recent_projects.addSeparator()
  8953. self.ui.recent_projects.addAction(clear_action_proj)
  8954. # Create menu items for files
  8955. for recent in self.recent:
  8956. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8957. if recent['kind'] != 'project':
  8958. try:
  8959. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8960. # Attach callback
  8961. o = make_callback(openers[recent["kind"]], recent['filename'])
  8962. action.triggered.connect(o)
  8963. self.ui.recent.addAction(action)
  8964. except KeyError:
  8965. App.log.error("Unsupported file type: %s" % recent["kind"])
  8966. # Last action in Recent Files menu is one that Clear the content
  8967. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), (_("Clear Recent files")), self)
  8968. clear_action.triggered.connect(reset_recent_files)
  8969. self.ui.recent.addSeparator()
  8970. self.ui.recent.addAction(clear_action)
  8971. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8972. # self.ui.menufilerecent.set_submenu(recent_menu)
  8973. # recent_menu.show_all()
  8974. # self.ui.recent.show()
  8975. self.log.debug("Recent items list has been populated.")
  8976. def setup_component_editor(self):
  8977. # label = QtWidgets.QLabel("Choose an item from Project")
  8978. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8979. sel_title = QtWidgets.QTextEdit(
  8980. _('<b>Shortcut Key List</b>'))
  8981. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8982. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8983. settings = QSettings("Open Source", "FlatCAM")
  8984. if settings.contains("notebook_font_size"):
  8985. fsize = settings.value('notebook_font_size', type=int)
  8986. else:
  8987. fsize = 12
  8988. tsize = fsize + int(fsize / 2)
  8989. # selected_text = (_('''
  8990. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  8991. #
  8992. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8993. # The normal flow when working in FlatCAM is the following:</span></p>
  8994. #
  8995. # <ol>
  8996. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  8997. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8998. # even dragging and dropping the files on the GUI.<br />
  8999. # <br />
  9000. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  9001. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  9002. # &nbsp;</li>
  9003. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  9004. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  9005. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  9006. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  9007. # <br />
  9008. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  9009. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  9010. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  9011. # it even if it was out of focus.<br />
  9012. # <br />
  9013. # You can change the parameters in this screen and the flow direction is like this:<br />
  9014. # <br />
  9015. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  9016. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  9017. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  9018. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  9019. # </ol>
  9020. #
  9021. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  9022. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  9023. # <strong>F3</strong>.</span></p>
  9024. #
  9025. # ''').format(fsize=fsize, tsize=tsize))
  9026. selected_text = '''
  9027. <p><span style="font-size:{tsize}px"><strong>%s</strong></span></p>
  9028. <p><span style="font-size:{fsize}px"><strong>%s</strong>:<br />
  9029. %s:</span></p>
  9030. <ol>
  9031. <li><span style="font-size:{fsize}px">%s menu&#39;s, %s.<br />
  9032. <br />
  9033. %s &amp; %s.</span><br />
  9034. &nbsp;</li>
  9035. <li><span style="font-size:{fsize}px">%s <strong>%s</strong> (%s), <strong>%s</strong> %s it-s %s.<br />
  9036. <br />
  9037. %s <strong>%s</strong> %s <strong>%s</strong> %s.<br />
  9038. <br />
  9039. %s:<br />
  9040. <br />
  9041. <strong>%s</strong> -&gt; %s -&gt; %s -&gt;<strong> %s </strong> -&gt; %s -&gt; %s -&gt;<strong> %s
  9042. </strong>-&gt; %s <strong>%s)&nbsp;</strong>-&gt; %s</span></li>
  9043. </ol>
  9044. <p><span style="font-size:{fsize}px">%s <strong>%s -&gt; %s</strong>&nbsp;%s it&#39;s %s:
  9045. <strong>F3</strong>.</span></p>
  9046. ''' % (
  9047. _("Selected Tab - Choose an Item from Project Tab"), _("Details"),
  9048. _("The normal flow when working in FlatCAM is the following"),
  9049. _("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the"),
  9050. _("toolbars, key shortcuts or even dragging and dropping the files on the GUI"),
  9051. _("You can also load a FlatCAM project by double clicking on the project file, drag"),
  9052. _("drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app"),
  9053. _("Once an object is available in the Project Tab, by selecting it and then focusing on"),
  9054. _("SELECTED TAB"), _("more simpler is to double click the object name in the Project Tab"),
  9055. _("SELECTED TAB"), _("will be updated with the object properties according to"),
  9056. _("kind: Gerber, Excellon, Geometry or CNCJob object"),
  9057. _("If the selection of the object is done on the canvas by single click instead, and the"),
  9058. _("SELECTED TAB"),
  9059. _("is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, "
  9060. "double clicking on the object on the canvas will bring the"),
  9061. _("SELECTED TAB"), _("and populate it even if it was out of focus"),
  9062. _("You can change the parameters in this screen and the flow direction is like this"),
  9063. _("Gerber/Excellon Object"), _("Change Parameter"), _("Generate Geometry"), _("Geometry Object"),
  9064. _("Add tools (change param in Selected Tab)"), _("Generate CNCJob"), _("CNCJob Object"),
  9065. _("Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in"), _("SELECTED TAB"),
  9066. _("Save GCode"), _("A list of key shortcuts is available through an menu entry in"), _("Help"),
  9067. _("Shortcuts List"), _("or through"), _("own key shortcut"),
  9068. )
  9069. sel_title.setText(selected_text)
  9070. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  9071. self.ui.selected_scroll_area.setWidget(sel_title)
  9072. def setup_obj_classes(self):
  9073. """
  9074. Sets up application specifics on the FlatCAMObj class.
  9075. :return: None
  9076. """
  9077. FlatCAMObj.app = self
  9078. ObjectCollection.app = self
  9079. Gerber.app = self
  9080. Excellon.app = self
  9081. Geometry.app = self
  9082. CNCjob.app = self
  9083. FCProcess.app = self
  9084. FCProcessContainer.app = self
  9085. def version_check(self):
  9086. """
  9087. Checks for the latest version of the program. Alerts the
  9088. user if theirs is outdated. This method is meant to be run
  9089. in a separate thread.
  9090. :return: None
  9091. """
  9092. self.log.debug("version_check()")
  9093. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  9094. full_url = App.version_url + \
  9095. "?s=" + str(self.defaults['global_serial']) + \
  9096. "&v=" + str(self.version) + \
  9097. "&os=" + str(self.os) + \
  9098. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  9099. else:
  9100. # no_stats dict; just so it won't break things on website
  9101. no_ststs_dict = {}
  9102. no_ststs_dict["global_ststs"] = {}
  9103. full_url = App.version_url + \
  9104. "?s=" + str(self.defaults['global_serial']) + \
  9105. "&v=" + str(self.version) + \
  9106. "&os=" + str(self.os) + \
  9107. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  9108. App.log.debug("Checking for updates @ %s" % full_url)
  9109. # ## Get the data
  9110. try:
  9111. f = urllib.request.urlopen(full_url)
  9112. except:
  9113. # App.log.warning("Failed checking for latest version. Could not connect.")
  9114. self.log.warning("Failed checking for latest version. Could not connect.")
  9115. self.inform.emit('[WARNING_NOTCL] %s' %
  9116. _("Failed checking for latest version. Could not connect."))
  9117. return
  9118. try:
  9119. data = json.load(f)
  9120. except Exception as e:
  9121. App.log.error("Could not parse information about latest version.")
  9122. self.inform.emit('[ERROR_NOTCL] %s' %
  9123. _("Could not parse information about latest version."))
  9124. App.log.debug("json.load(): %s" % str(e))
  9125. f.close()
  9126. return
  9127. f.close()
  9128. # ## Latest version?
  9129. if self.version >= data["version"]:
  9130. App.log.debug("FlatCAM is up to date!")
  9131. self.inform.emit('[success] %s' %
  9132. _("FlatCAM is up to date!"))
  9133. return
  9134. App.log.debug("Newer version available.")
  9135. self.message.emit(
  9136. _("Newer Version Available"),
  9137. _("There is a newer version of FlatCAM available for download:\n\n") +
  9138. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  9139. _("info")
  9140. )
  9141. def on_plotcanvas_setup(self, container=None):
  9142. """
  9143. This is doing the setup for the plot area (VisPy canvas)
  9144. :param container: widget where to install the canvas
  9145. :return: None
  9146. """
  9147. if container:
  9148. plot_container = container
  9149. else:
  9150. plot_container = self.ui.right_layout
  9151. if self.is_legacy is False:
  9152. self.plotcanvas = PlotCanvas(plot_container, self)
  9153. else:
  9154. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  9155. # So it can receive key presses
  9156. self.plotcanvas.native.setFocus()
  9157. self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  9158. self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  9159. self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  9160. self.plotcanvas.graph_event_connect('mouse_double_click', self.on_double_click_over_plot)
  9161. # Keys over plot enabled
  9162. self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  9163. self.app_cursor = self.plotcanvas.new_cursor()
  9164. if self.ui.grid_snap_btn.isChecked():
  9165. self.app_cursor.enabled = True
  9166. else:
  9167. self.app_cursor.enabled = False
  9168. if self.is_legacy is False:
  9169. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  9170. else:
  9171. self.hover_shapes = ShapeCollectionLegacy()
  9172. def on_zoom_fit(self, event):
  9173. """
  9174. Callback for zoom-out request. This can be either from the corresponding
  9175. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  9176. with axes limits from the geometry bounds of all objects.
  9177. :param event: Ignored.
  9178. :return: None
  9179. """
  9180. self.plotcanvas.fit_view()
  9181. def on_zoom_in(self):
  9182. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  9183. def on_zoom_out(self):
  9184. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  9185. def disable_all_plots(self):
  9186. self.report_usage("disable_all_plots()")
  9187. self.disable_plots(self.collection.get_list())
  9188. self.inform.emit('[success] %s' %
  9189. _("All plots disabled."))
  9190. def disable_other_plots(self):
  9191. self.report_usage("disable_other_plots()")
  9192. self.disable_plots(self.collection.get_non_selected())
  9193. self.inform.emit('[success] %s' %
  9194. _("All non selected plots disabled."))
  9195. def enable_all_plots(self):
  9196. self.report_usage("enable_all_plots()")
  9197. self.enable_plots(self.collection.get_list())
  9198. self.inform.emit('[success] %s' %
  9199. _("All plots enabled."))
  9200. def on_enable_sel_plots(self):
  9201. log.debug("App.on_enable_sel_plot()")
  9202. object_list = self.collection.get_selected()
  9203. self.enable_plots(objects=object_list)
  9204. self.inform.emit('[success] %s' %
  9205. _("Selected plots enabled..."))
  9206. def on_disable_sel_plots(self):
  9207. log.debug("App.on_disable_sel_plot()")
  9208. # self.inform.emit(_("Disabling plots ..."))
  9209. object_list = self.collection.get_selected()
  9210. self.disable_plots(objects=object_list)
  9211. self.inform.emit('[success] %s' %
  9212. _("Selected plots disabled..."))
  9213. def enable_plots(self, objects):
  9214. """
  9215. Disables plots
  9216. :param objects: list of Objects to be enabled
  9217. :return:
  9218. """
  9219. log.debug("Enabling plots ...")
  9220. # self.inform.emit(_("Working ..."))
  9221. for obj in objects:
  9222. if obj.options['plot'] is False:
  9223. obj.options.set_change_callback(lambda x: None)
  9224. obj.options['plot'] = True
  9225. obj.options.set_change_callback(obj.on_options_change)
  9226. def worker_task(objects):
  9227. with self.proc_container.new(_("Enabling plots ...")):
  9228. for obj in objects:
  9229. # obj.options['plot'] = True
  9230. if isinstance(obj, FlatCAMCNCjob):
  9231. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  9232. else:
  9233. obj.plot(visible=True)
  9234. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9235. # self.plots_updated.emit()
  9236. def disable_plots(self, objects):
  9237. """
  9238. Disables plots
  9239. :param objects: list of Objects to be disabled
  9240. :return:
  9241. """
  9242. # if no objects selected then do nothing
  9243. if not self.collection.get_selected():
  9244. return
  9245. log.debug("Disabling plots ...")
  9246. # self.inform.emit(_("Working ..."))
  9247. for obj in objects:
  9248. if obj.options['plot'] is True:
  9249. obj.options.set_change_callback(lambda x: None)
  9250. obj.options['plot'] = False
  9251. obj.options.set_change_callback(obj.on_options_change)
  9252. try:
  9253. self.delete_selection_shape()
  9254. except Exception as e:
  9255. log.debug("App.disable_plots() --> %s" % str(e))
  9256. # self.plots_updated.emit()
  9257. def worker_task(objects):
  9258. with self.proc_container.new(_("Disabling plots ...")):
  9259. for obj in objects:
  9260. # obj.options['plot'] = True
  9261. if isinstance(obj, FlatCAMCNCjob):
  9262. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  9263. else:
  9264. obj.plot(visible=False)
  9265. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  9266. def toggle_plots(self, objects):
  9267. """
  9268. Toggle plots visibility
  9269. :param objects: list of Objects for which to be toggled the visibility
  9270. :return:
  9271. """
  9272. # if no objects selected then do nothing
  9273. if not self.collection.get_selected():
  9274. return
  9275. log.debug("Toggling plots ...")
  9276. self.inform.emit(_("Working ..."))
  9277. for obj in objects:
  9278. if obj.options['plot'] is False:
  9279. obj.options['plot'] = True
  9280. else:
  9281. obj.options['plot'] = False
  9282. self.plots_updated.emit()
  9283. def clear_plots(self):
  9284. objects = self.collection.get_list()
  9285. for obj in objects:
  9286. obj.clear(obj == objects[-1])
  9287. # Clear pool to free memory
  9288. self.clear_pool()
  9289. def generate_cnc_job(self, objects):
  9290. self.report_usage("generate_cnc_job()")
  9291. # for obj in objects:
  9292. # obj.generatecncjob()
  9293. for obj in objects:
  9294. obj.on_generatecnc_button_click()
  9295. def save_project(self, filename, quit_action=False, silent=False):
  9296. """
  9297. Saves the current project to the specified file.
  9298. :param filename: Name of the file in which to save.
  9299. :type filename: str
  9300. :param quit_action: if the project saving will be followed by an app quit; boolean
  9301. :param silent: if True will not display status messages
  9302. :return: None
  9303. """
  9304. self.log.debug("save_project()")
  9305. self.save_in_progress = True
  9306. with self.proc_container.new(_("Saving FlatCAM Project")):
  9307. # Capture the latest changes
  9308. # Current object
  9309. try:
  9310. self.collection.get_active().read_form()
  9311. except:
  9312. self.log.debug("There was no active object")
  9313. pass
  9314. # Project options
  9315. self.options_read_form()
  9316. # Serialize the whole project
  9317. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  9318. "options": self.options,
  9319. "version": self.version}
  9320. if self.defaults["global_save_compressed"] is True:
  9321. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  9322. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  9323. # # Write
  9324. f.write(g)
  9325. self.inform.emit('[success] %s: %s' %
  9326. (_("Project saved to"), filename))
  9327. else:
  9328. # Open file
  9329. try:
  9330. f = open(filename, 'w')
  9331. except IOError:
  9332. App.log.error("Failed to open file for saving: %s", filename)
  9333. return
  9334. # Write
  9335. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  9336. f.close()
  9337. # verification of the saved project
  9338. # Open and parse
  9339. try:
  9340. saved_f = open(filename, 'r')
  9341. except IOError:
  9342. if silent is False:
  9343. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9344. (_("Failed to verify project file"), filename, _("Retry to save it."))
  9345. )
  9346. return
  9347. try:
  9348. saved_d = json.load(saved_f, object_hook=dict2obj)
  9349. except:
  9350. if silent is False:
  9351. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9352. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9353. )
  9354. f.close()
  9355. return
  9356. saved_f.close()
  9357. if silent is False:
  9358. if 'version' in saved_d:
  9359. self.inform.emit('[success] %s: %s' %
  9360. (_("Project saved to"), filename))
  9361. else:
  9362. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  9363. (_("Failed to parse saved project file"), filename, _("Retry to save it."))
  9364. )
  9365. settings = QSettings("Open Source", "FlatCAM")
  9366. lock_state = self.ui.lock_action.isChecked()
  9367. settings.setValue('toolbar_lock', lock_state)
  9368. # This will write the setting to the platform specific storage.
  9369. del settings
  9370. # if quit:
  9371. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  9372. # t.start()
  9373. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  9374. def start_delayed_quit(self, delay, filename, should_quit=None):
  9375. """
  9376. :param delay: period of checking if project file size is more than zero; in seconds
  9377. :param filename: the name of the project file to be checked periodically for size more than zero
  9378. :param should_quit: if the task finished will be followed by an app quit; boolean
  9379. :return:
  9380. """
  9381. to_quit = should_quit
  9382. self.save_timer = QtCore.QTimer()
  9383. self.save_timer.setInterval(delay)
  9384. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  9385. self.save_timer.start()
  9386. def check_project_file_size(self, filename, should_quit=None):
  9387. """
  9388. :param filename: the name of the project file to be checked periodically for size more than zero
  9389. :param should_quit: will quit the app if True; boolean
  9390. :return:
  9391. """
  9392. try:
  9393. if os.stat(filename).st_size > 0:
  9394. self.save_in_progress = False
  9395. self.save_timer.stop()
  9396. if should_quit:
  9397. self.app_quit.emit()
  9398. except Exception as e:
  9399. traceback.print_exc()
  9400. def on_options_app2project(self):
  9401. """
  9402. Callback for Options->Transfer Options->App=>Project. Copies options
  9403. from application defaults to project defaults.
  9404. :return: None
  9405. """
  9406. self.report_usage("on_options_app2project")
  9407. self.defaults_read_form()
  9408. self.options.update(self.defaults)
  9409. self.options_write_form()
  9410. def on_options_project2app(self):
  9411. """
  9412. Callback for Options->Transfer Options->Project=>App. Copies options
  9413. from project defaults to application defaults.
  9414. :return: None
  9415. """
  9416. self.report_usage("on_options_project2app")
  9417. self.options_read_form()
  9418. self.defaults.update(self.options)
  9419. self.defaults_write_form()
  9420. def on_options_project2object(self):
  9421. """
  9422. Callback for Options->Transfer Options->Project=>Object. Copies options
  9423. from project defaults to the currently selected object.
  9424. :return: None
  9425. """
  9426. self.report_usage("on_options_project2object")
  9427. self.options_read_form()
  9428. obj = self.collection.get_active()
  9429. if obj is None:
  9430. self.inform.emit('[WARNING_NOTCL] %s' %
  9431. _("No object selected."))
  9432. return
  9433. for option in self.options:
  9434. if option.find(obj.kind + "_") == 0:
  9435. oname = option[len(obj.kind) + 1:]
  9436. obj.options[oname] = self.options[option]
  9437. obj.to_form() # Update UI
  9438. def on_options_object2project(self):
  9439. """
  9440. Callback for Options->Transfer Options->Object=>Project. Copies options
  9441. from the currently selected object to project defaults.
  9442. :return: None
  9443. """
  9444. self.report_usage("on_options_object2project")
  9445. obj = self.collection.get_active()
  9446. if obj is None:
  9447. self.inform.emit('[WARNING_NOTCL] %s' %
  9448. _("No object selected."))
  9449. return
  9450. obj.read_form()
  9451. for option in obj.options:
  9452. if option in ['name']: # TODO: Handle this better...
  9453. continue
  9454. self.options[obj.kind + "_" + option] = obj.options[option]
  9455. self.options_write_form()
  9456. def on_options_object2app(self):
  9457. """
  9458. Callback for Options->Transfer Options->Object=>App. Copies options
  9459. from the currently selected object to application defaults.
  9460. :return: None
  9461. """
  9462. self.report_usage("on_options_object2app")
  9463. obj = self.collection.get_active()
  9464. if obj is None:
  9465. self.inform.emit('[WARNING_NOTCL] %s' %
  9466. _("No object selected."))
  9467. return
  9468. obj.read_form()
  9469. for option in obj.options:
  9470. if option in ['name']: # TODO: Handle this better...
  9471. continue
  9472. self.defaults[obj.kind + "_" + option] = obj.options[option]
  9473. self.defaults_write_form()
  9474. def on_options_app2object(self):
  9475. """
  9476. Callback for Options->Transfer Options->App=>Object. Copies options
  9477. from application defaults to the currently selected object.
  9478. :return: None
  9479. """
  9480. self.report_usage("on_options_app2object")
  9481. self.defaults_read_form()
  9482. obj = self.collection.get_active()
  9483. if obj is None:
  9484. self.inform.emit('[WARNING_NOTCL] %s' %
  9485. _("No object selected."))
  9486. return
  9487. for option in self.defaults:
  9488. if option.find(obj.kind + "_") == 0:
  9489. oname = option[len(obj.kind) + 1:]
  9490. obj.options[oname] = self.defaults[option]
  9491. obj.to_form() # Update UI
  9492. class ArgsThread(QtCore.QObject):
  9493. open_signal = pyqtSignal(list)
  9494. start = pyqtSignal()
  9495. if sys.platform == 'win32':
  9496. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  9497. else:
  9498. address = ('/tmp/testipc', 'AF_UNIX')
  9499. def __init__(self):
  9500. super(ArgsThread, self).__init__()
  9501. self.start.connect(self.run)
  9502. def my_loop(self, address):
  9503. try:
  9504. listener = Listener(*address)
  9505. while True:
  9506. conn = listener.accept()
  9507. self.serve(conn)
  9508. except socket.error as e:
  9509. conn = Client(*address)
  9510. conn.send(sys.argv)
  9511. conn.send('close')
  9512. # close the current instance only if there are args
  9513. if len(sys.argv) > 1:
  9514. sys.exit()
  9515. def serve(self, conn):
  9516. while True:
  9517. msg = conn.recv()
  9518. if msg == 'close':
  9519. break
  9520. self.open_signal.emit(msg)
  9521. conn.close()
  9522. # the decorator is a must; without it this technique will not work unless the start signal is connected
  9523. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  9524. @pyqtSlot()
  9525. def run(self):
  9526. self.my_loop(self.address)
  9527. class GracefulException(Exception):
  9528. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  9529. def __init__(self):
  9530. super().__init__()
  9531. def __str__(self):
  9532. return ('\n\n%s' % _("The user requested a graceful exit of the current task."))
  9533. # end of file